Dealing with immutable collections in Java

11 / Apr / 2012 by Salil 0 comments

Perhaps, you know it before or just skipped it after going through Java API. But I really found it very helpful at this point.

 

Recently, I had a requirement in an open-source project, where users can iterate through the objects saved in collections (esp. List). But the problem was, we really didn’t want users to directly or indirectly update those collection objects. Or in other words, we wanted to provide them collections with Read-Only behavior.

 

So to fulfill this requirement, I had few solutions –
1) Writing a wrapper class for iterating the objects in collection, in a manner that it behaves like Immutable collection objects.
2) Implementing your own Collection classes to support read-only behavior.
3) Returning the output as Iterable.
4) And many more – as complicated as we want to make it.

 

Well, need not to worry guys!
Java provides an in-built class “java.util.Collections – to deal with such kind of problems.

Collections class comes up with a good list of static methods. Like, for converting a modifiable list to unmodifiable list (read-only list), we have following method:
[java]
List myUnmodifiableList = Collections.unmodifiableList(myModifiableList)
[/java]

and now, if anyone will try to modify ‘myUnmodifiableList’, it will throw UnsupportedOperationException.
Similarly, there are other methods to handle different types of collections.

 

I hope this might help someone.

 

Please put your comment, if there’s any better way out there.

 

Cheers!
Salil Kalia
Salil [at] IntelliGrape [dot] com
Twitter LinkedIn

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *