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)

 

 

References:

https://docs.oracle.com/javase/tutorial/collections/intro/
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html
http://docs.oracle.com/javase/7/docs/api/index.html?java/util/class-use/LinkedHashSet.html

 

Happy Coding !!
Happy Learning !!