Class HighLite Collections
When working with the Java Collections API, you often need to sort, shuffle, or reserve a list. For these and other tasks you can use a class aptly named Collections made available in the java.util package. The Collections class is like the Math class in that it provides a large number of static methods. The Collections class provides convenience static methods for working with any of the Collections API classes such as List, Map, and Set. For this Class HighLite I want to focus on the methods that make an immutable, synchronized, or singleton collection.
Immutable Lists
Item 13, Favor Immutability, in Joshua Bloch’s book Effective Java describes the benefits of writing and using immutable classes, that classes whose instances cannot be modified after creation. In general, immutable objects tend to be thread safe. In my experience, I have seen far too many insidious bugs related to cached/global/singleton mutable objects. These bugs usually happen because some code updates a global object which in turn invalidates the state of another resource. As a rule of thumb, I never cache, pool, or use as singleton mutable objects.
Creating immutable classes is easy if you are dealing with Strings (immutable) and primitives values. If you are dealing with any of the Collections API classes such as list, map, or set, you need to make that collection unmodifiable. Here is how to return an immutable list back to a calling code block.
[source:java]
public List getFieldNames() {
return Collections.unmodifiableList(this.fieldnames);
}
[/source]
Trying to modify an unmodifiable list by adding, setting, removing values would generate a run time exception, UnsupportedOperationException.
Synchronized Sets
Synchronized objects provide an additional level of thread-safety. The Collections class can provide a synchronized collections wrapper for any list, map, or set. One word of caution, you still need to call synchronized keyword on a synchronized wrapper to your list. That last sentence might be a bit confusing, so let me try to clarify it with some code.
[source:java]
List syncSet = Collections.synchronizedSet(myStringSet);
synchronized(syncSet) {
for(Iterator i = syncSet.iterator(); i.hasNext(); ) {
String str = (String)i.next();
}
}
[/source]
Singleton Maps
The Java Collections class has a series of methods to create a ‘singleton’ set, list, and map. A singleton collection object is immutable and has just one value. Here is an example of a singleton map.
[source:java]
Map map = Collections.singletonMap(myKey, myValue);
[/source]
Since the above singleton map is immutable, it will throw an UnsupportedOperationException when you try to put new values into the map.
Technorati Tags: collections, collections api, api, java, util, highlite, learning java, java tutorial