Tuesday, October 27, 2015

Core Java - What are best practices related to Java Collections Framework?



1.               Chosing the right type of collection based on the need, for example if size is fixed, we might want to use Array over ArrayList. If we have to iterate over the Map in order of insertion, we need to use TreeMap. If we don’t want duplicates, we should use Set.
2.    Some collection classes allows to specify the initial capacity, so if we have an estimate of number of elements we will store, we can use it to avoid rehashing or resizing.
3.    Write program in terms of interfaces not implementations, it allows us to change the implementation easily at later point of time.
4.    Always use Generics for type-safety and avoid ClassCastException at runtime.
5.    Use immutable classes provided by JDK as key in Map to avoid implementation of hashCode() and equals() for our custom class.
6.    Use Collections utility class as much as possible for algorithms or to get read-only, synchronized or empty collections rather than writing own implementation. It will enhance code-reuse with greater stability and low maintainability.

No comments:

Post a Comment