HashSet v/s LinkedHashSet

In this article, we will discuss difference between HashSet and LinkedHashSet classes in detail i.e.; HashSet v/s LinkedHashSet

Lets us move on and discuss key differences between these 2 Set implemented collection classes



HashSet v/s LinkedHashSet

HashSet LinkedHashSet
Uses hash table (acutally HashMap instance) to store element/objects Uses combination of hash table + LinkedList to store element/objects
Doesn’t maintain insertion order i.e.; while iterating through HashSet, we will get items in random order Since, it uses doubly-linked list to store elements, maintains insertion order
This is introduced in the original collection framework in Java 1.2 version This is introduced in Java 1.4 version


When to use HashSet?

  • HashSet stores unique elements using hashing technique
  • So, search operation is faster
  • So, if business requirement is to store unique elements for faster search operation or more number of search operation without concerning insertion order
  • Then, HashSet is the very apt choice


When to use LinkedHashSet?

  • This is exactly same as that of HashSet, but underlying data structure to hold items is different
  • It uses doubly-linked list which allows to hold items as per insertion order
  • So, if business requirement is to store unique elements for faster search operation or more number of search operation concerning/maintaining insertion order
  • Then, LinkedHashSet is the very apt choice which maintains insertion order
  • So while iterating through LinkedHashSet, we will get items as per insertion order (as against random in HashSet)






Happy Coding !!
Happy Learning !!