Different Types of Collections and when to Use them
Set
HashSet :
Set
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
TreeSet:
- 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
LinkedHashSet
- This gives us the flexibility of HashSet (uniqueness) and
- also maintains the insertion-order of objects
Map
HashMap :
- Easier way of holding Key Value Pair
- Does not maintain the insertion-order (Hashed)
TreeMap:
- 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()
LinkedHashMap:
- Extends HashMap. But, preserves of the insertion order
List:
ArrayList:
- 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()
LinkedList:
- Performs better when you have more additions and insertions than searching the list
No comments:
Post a Comment