HashSet vs TreeSet vs LinkedHashSet in Java | Java @ Desk
Home » , » HashSet vs TreeSet vs LinkedHashSet in Java

HashSet vs TreeSet vs LinkedHashSet in Java

HashSet vs TreeSet vs LinkedHashSet in Java

java.util.HashSet, java.util.LinkedHashSet, java.util.TreeSet implements the Set interface in Java. All 3 implementation fulfill the basic principal of a Set interface by not allowing duplicates enteries. The add() method returns a boolean. In case of duplicate entry, the add() method returns false.

Difference between the three :

1) How duplicates are detected internally while adding an element

When add() method is called among the three internally, HashSet and LinkedHashSet uses the .equals() to compare if the object is present or not. If the element is present .equals() method returns true and the element is not added.

But TreeSet uses .compareTo(). If the method returns 0, the element is present and it is not added. If it returns -1 or +1, it performs the sorting of elements.

2) Sorting and Ordering of Elements

HashSet does not maintains any order of elements. Every time a new element is added, the order of elements may or may not be changed. LinkedHashSet strictly maintains inserion order of elements. TreeSet also does not maintains insertion order, it sorts the element and maintain sorting order

HashSet -> Does not maintain insertion order
LinkedHashSet -> Maintains insertion order
TreeSet -> Does not maintain insertion order as it sorts the elements inserted.

3) Null Elements

As discussed in point 1, while adding an element in HashSet or LinkedHashSet .equals() method is used. So it allows null elements insertion.

But in TreeSet, it uses .compareTo(). So when null is inserted .compareTo() method is called on it resulting in NullPointerException

HashSet -> Allow Null
LinkedHashSet -> Allow Null
TreeSet -> Does not Allow Null. Throws RuntimeException (NullPointerException).

4) Performance

TreeSet is slowest because everytime .add() method is called to insert an element it needs to sort the complete Set. If the Set is of 10000 elements, complete sorting will be required.

LinkedHashSet is at second while HashSet is at the top performance wise.


Post a Comment