Saturday, 21 September 2013

Quick Notes : Practical usage of collections

Different Types of Collections and when to Use them


HashSet : 

  • When you want unique set to objects. 
  • Make sure equals and hashcode is implemented.
  • This does not maintain the order of object addition. As the name says it is Hashed

  • You can have the list ordered the way you want, by passing in a comparator.
  • Example: new TreeSet(String.CASE_INSENSITIVE_ORDER)
  • It automatically orders the objects that you add accordingly

  • This gives us the flexibility of HashSet (uniqueness) and 
  • also maintains the insertion-order of objects


HashMap :
  • Easier way of holding Key Value Pair
  • Does not maintain the insertion-order (Hashed)
  • Sorted Map, Sorting of keys determined by the comparator in the constructor
  • Quickly create a map of case insensitive keys as follows
    new TreeMap(String.CASE_INSENSITIVE_ORDER)
  • Throws a NullPointerException if you use get without a null check.
    treemap.get(null), so better add a null check before invoking get()
  • Extends HashMap. But, preserves of the insertion order


  • Quicker way of maintaining a list of objects
  • can add duplicate values.
  • It is advisable to use this collection if we expect more number of gets() than add() or set()
  • Performs better when you have more additions and insertions than searching the list

No comments:

Post a Comment