Linkedhashset Java: In this article, we will discuss the difference between HashSet and LinkedHashSet classes in detail i.e.; HashSet v/s LinkedHashSet. Lets us move on and discuss the key differences between these 2 Set implemented collection classes.
Read Also: List Vs Set In Java
HashSet vs LinkedHashSet
|Uses hash table (actually HashMap instance) to store element/objects||Uses a 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 a 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|
Check Also: selenium interview questions for experienced
When to use HashSet?
- HashSet stores unique elements using a hashing technique
- So, the search operation is faster
- So, if the 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
Read Also: HashSet vs Linkedhashset
When to use LinkedHashSet?
- This is exactly the same as that of HashSet, but underlying data structure to hold items is different
- It uses a doubly-linked list which allows holding items as per insertion order
- So, if the 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)