Thursday, August 10, 2006

What are some of the best practices relating to Java collection?

1. Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc, where possible to avoid
any synchronization overhead. Even better is to use just arrays where possible. If multiple
threads concurrently access a collection and at least one of the threads either adds or deletes
an entry into the collection, then the collection must be externally synchronized. This is
achieved by:

Map myMap = Collections.synchronizedMap (myMap);
List myList = Collections.synchronizedList (myList);

2. Set the initial capacity of a collection appropriately (e.g. ArrayList, HashMap etc). This is because collection classes like ArrayList, HashMap etc must grow periodically to accommodate new elements. But if you have a very large array, and you know the size in advance then you can speed things up by setting the initial size appropriately.

3. Program in terms of interface not implementation

4. Avoid storing unrelated or different types of objects into same collection


0 Comments:

Post a Comment

<< Home