Static factory methods vs Java collection API
February 5, 2007
Some of the features like searching, sorting, shuffling, immutability etc are achieved with java.util.Collections class and java.util.Arrays utility classes. The great majority of these implementations are provided via static factory methods in a single, non-instantiable (i.e. private constrctor) class. Speaking of static factory methods, they are an alternative to creating objects through constructors. Unlike constructors, static factory methods are not required to create a new object (i.e. a duplicate object) each time they are invoked (i.e. immutable instances can be cached) and also they have a more meaningful names.
For example to print an array, instead of looping through, you could write something like this.
String[] myArray = {“A”,”B”, “C”};
System.out.println(Arrays.asList(myArray));
What are some of the best practices relating to Java collection?
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
Program in terms of interface not implementation: For example you might decide a LinkedList is the best choice for some application, but then later decide ArrayList might be a better choice for performance reason.
Use:
List list = new ArrayList(100); // program in terms of interface & set the initial capacity.
Instead of:
ArrayList list = new ArrayList();
Entry Filed under: Uncategorized. .

Trackback this post | Subscribe to the comments via RSS Feed