Sr No. | HashSet | LinkedHashSet | TreeSet |
Internal Working | HashSet 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. |
order | HashSet 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 elements | allow one null value. | allow one null value. | TreeSet doesn’t allow null elements. it throws nullPointerException. |
compare | uses equals() and hashCode() | uses equals() and hashCode() | It uses the compare() and compareTo() methods to compare objects. |