Archive for the ‘Collections’ Category
Null returned from a method returning a collection or an array
Null should never be returned from a method returning a collection or an array. Instead return a empty array (a static final empty array) or one of the empty collections (e.g. Collections.EMPTY_LIST assuming the client should not be modifying the collection).
(submitted by Rand McNeely)
Using URLs in Collections
java.net.URL objects used as Map keys or Set items can result in a big performance issue. Internal implementation of equals() and hashCode() methods of java.net.URL class performs domain name resolution, so the time of their execution relies on an internet connection speed. If a computer is off-line, the time is nearly equal to a connection timeout (tens of seconds).
The same problem arises every time when URLs equality checking or hash code computation is performed.
Do not use java.net.URL to keep URL values. Use java.net.URI objects or the simple Strings instead.
Accessing the Map values using keySet iterator
A common mistake is to retrieve values from a Map while iterating over the Map keys with keySet(). Calling Map.get(key) for each entry is expensive and should be avoided for better performance.
Use entrySet() iterator to avoid the Map.get(key) lookup.
Synchronized collections everywhere
Vector and Hashtable are just the synchronized versions of the ArrayList an HashMap but working much slower. Use unsynchronized collections unless thread-safety is really required.