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 remove Method is Implemented in a HashMap in Java ?

What are the Differences Between Comparable and Comparator in Jav ...

How Can Be Read Data From a Form in a JSP ?

What is the Difference Between Iterator and Enumeration in Java ?

How Does Web Module Work in Spring Framework ?