hashset and linkedhashset differences in java

By | May 27, 2019

Differences between HashSet and LinkedHashSet in Java:

 

S.No HashSet LinkedHashSet
1 HashSet doesn’t maintain insertion order. LinkedHashSet maintains insertion order.
2 Unordered. Order is unpredictable when we iterate through the elements. Ordered and gives predictable output.
3 If you don’t want to maintain insertion order and should have unique values then you can use HashSet. If you want insertion order then you can go with LinkedHashSet.

Example:

Output:

HashSet is: [Three, One, Four, Two]

LinkedHashSet is: [One, Two, Three, Four]

Printing elements using iterator.
One
Two
Three
Four

Leave a Reply

Your email address will not be published. Required fields are marked *