Comparing HashSet and TreeSet Collections in Java

A HashSet is Implemented using a HashTable. Therefore, its elements are stored in a random order. The add(), remove(), and contains() methods of a HashSet have constant time complexity O(1).

A TreeSet is implemented using a tree data structure. The elements in a TreeSet are sorted in a natural order. Therefore, add(), remove(), and contains() methods have time complexity of O(logn).

So from performance perspective, HashSet has better performance than TreeSet. But if you want to store elements in a natural sorting order, then TreeSet is a better collection.



You May Interest

How Can We Find the Memory Usage of JVM From Java Code ?

What are the Disadvantages of Multithreading in Java ?

What is the Difference Between StringBuffer and StringBuilder in ...

What is the Difference Between wait and sleep Methods in Java ?

What is the Use of Run Time Polymorphism in Java ?