HashSet LinkedHashSet and TreeSet differences

Sr No.HashSetLinkedHashSetTreeSet
Internal WorkingHashSet internally uses HashMap for storing objects.LinkesHashSet uses LinkedHashMap internally for storing the object.TreeSet internally uses TreeMap to store objects.
When to use when you do not want to maintain insertion order but want to store unique objects.when you want to maintain the insertion order in that case you can use LinkedHashSet.when you want to sort elements based on some Comparator in that case you can use TreeSet.
orderHashSet doesn’t maintain insertion order.LinkedHashSet maintains insertion order.While TreeSet orders elements according to the supplied Comparator. By default, objects will be placed based on the natural ascending order.
Null elementsallow one null value.allow one null value.TreeSet doesn’t allow null elements.
it throws nullPointerException.
compareuses equals() and hashCode()uses equals() and hashCode()It uses the compare() and compareTo() methods to compare objects.

Author: Susheel kumar

Leave a Reply

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