61. Compare Hash Set, LinkedHashSet and TreeSet

Compare Hash Set, LinkedHashSet and TreeSet?

 

 

 

HashSet LinkedHashSet TreeSet
How to work? uses HashMap internally to store elements. uses LinkedHashMap internally to store elements. uses TreeMap internally to store elements.
Order Of Elements HashSet does not maintain any order in which elements were added. LinkedHashSet maintains the insertion order of the elements. Elements are stored in the correct order in which they were inserted. TreeSet maintains the order of elements according to the provided comparator (Comparator). If no comparator is provided, the elements will be placed in their natural ascending order.
Performance HashSet gives better performance than LinkedHashSet and TreeSet. LinkedHashSet falls between HashSet and TreeSet. Its performance is almost similar to HashSet. But slightly slower as it also maintains an internal LinkedList to maintain the insertion sequence of the elements. TreeSet gives lower performance than HashSet and LinkedHashSet because it has to sort the elements after each insertion and removal.
Insertion, Removal and Retrieval element operations O(1) performance for inserting, removing, and retrieving elements. LinkedHashSet also offers O(1) performance for inserting, removing, and retrieving elements. TreeSet gives O(log(n)) performance for insert, remove, and retrieve elements.
Compare elements HashSet uses equals() and hashCode() methods to compare elements and thus remove possible duplicates. LinkedHashSet also uses equals() and hashCode() methods to compare elements. TreeSet uses compare() or compareTo() methods to compare elements and thus remove possible duplicates.

Leave a Reply

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