Differences and Similarities between HashSet TreeSet and LinkedHashSet


TreeSet, LinkedHashSet and HashSet are implementation of Set interface from that, they follows contract of Set interface i.e. they do not allow duplicate elements.
Now in this post we will see the difference between HashSet, TreeSet and LinkedHashSet on different points like ordering elements, allowing null and performance ..etc.

Details of HashSet TreeSet and LinkedHashSet:
Main feature of HashSet is storing unique objects, Main feature of TreeSet is ordering, and LinkedHashSet is insertion order.
  • HashSet has backing HashMap instance and default initial capacity (16) and load factor (0.75).
  • LinkedHashSet is Hash table and linked list implementation of the Set interface, with predictable iteration order. It maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. [An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.] default initial capacity (16) and load factor (0.75).

Similarities between HashSet TreeSet and LinkedHashSet:

  • Not allowed to store duplicates.
  • Not Thread-safe need external synchronization.
  • Fail-fast iterator and throw ConcurrentModificationException.

Difference between HashSet TreeSet and LinkedHashSet:

Ordering Performance Null Internal Implementaion
HashSet Doesn’t Maintain Fastest O(1) Allow backing of HashMap
LinkedHashSet Insertion Order Fastest O(1) (Similar to HashSet) Allow backing of HashSet and LinkedList
TreeSet Sorting order of elements Slower O(log(n)) (slow due to sorting) Doesn’t Allow backing of NavigableMap and TreeMap

Please refer HashSetTreeSet, and LinkedHashSet for more details.
img logo

No comments :

Post a Comment