Best practices while using collection API

The following are some best practices that one can follow while using collection API (as discussed in various blogs and books)

  1. Code to interfaces rather than implementation; reason, you can change the implementation later on without significant effect.
  2. Set the initial capacity of the collection appropriately, if you know the size you can gain on speed, else these collection classes will have to grow periodically when the size hits the limit.
  3. Use ArrayList, HashMap etc as opposed to Vector and Hashtable; reason,Vector and Hashtable methods are synchronized, if you want synchronization using ArrayList, HashMap then you externally synchronize the same. I will show that in my next blog.
  4. Return zero length collection or array as opposed to returning NULL; to avoid running into NullPointerException issues at runtime.
  5. Immutable object should be used as keys for the HashMap; so also as values in a HashSet. 
  6. Encapsulate collections; to avoid unintentional  modification of the collections.
  7. Stored related objects together and avoid storing unrelated or different types in the same collection.


Popular posts from this blog

How does HashMap work in Java

Immutable classes

Equals and hashcode method