We have read HashSet and LinkedHashSet in recent posts. In this post, we will see what is the difference between HashSet and LinkedHashSet or HashSet vs LinkedHashSet? Both has different use and implementation in JDK. Let’s see how HashSet vs LinkedHashSet
1. The HashSet class doesn’t maintain the order of elements. If you iterate a HashSet then it can retrieve elements in any order. We can arrange the order of the elements.
But LinkedHashSet maintains the insertion order of elements. When we traverse the element from LinkedHashSet, it retrieves the element in insertion order.
2. HashSet class uses the HashMap internally and operate all the data in HashMap.
But A LinkedHashSet internally uses the LinkedHashMap and doubly linked list. It performs all the operations on LinkedHashMap.
3. When you want to store the unique element and you don’t want to maintain any order of the element. Then you should use HashSet because it is an unordered collection.
But when you want to store unique elements with their insertion order then you should use LinkedHashSet.
4. The performance of HashSet is faster than LinkedHashSet because LinkedHashSet maintains insertion order in the linked list.
5. The LinkedHashSet consume more memory than the HashSet.
6. The HashSet introduced in JDK 1.2 but LinkedHashSet introduced in JDK 1.4.