HashSet vs TreeSet | Java
This post will list the similarities and differences between HashSet and TreeSet implementation of the Set interface in Java.
Similarities:
Let’s start this post by discussing the similarities between HashSet and TreeSet classes:
HashSetandTreeSetare members of the Java Collections Framework and implementsjava.util.Setinterface.- They don’t permit any duplicates values.
- Implementations of
HashSetandTreeSetare not synchronized. - Both
HashSetandTreeSetcan be wrapped using theCollections.synchronizedSortedSet()method to make them thread-safe. - The iterators returned by
HashSetandTreeSetiterator methods are fail-fast. Fail-fast iterators throwConcurrentModificationExceptionif the set is modified after the iterator is created without using iterator’sremove()method.
Differences:
Now let’s discuss some of the major differences between HashSet and TreeSet implementations.
HashSetinternally uses aHashMapinstance, whereasTreeSetimplementation is based on aTreeMap.- The iteration order of the
HashSetis undefined, whereas elements ofTreeSetare ordered using their natural ordering or according to the specified Comparator. - The time taken by
HashSetfor the majority of common set operations such as add, remove, contains, etc., is constant, whereasTreeSettakes O(log(n)) time for these operations. HashSetallows a null value, whereasTreeSetsupports null value only if its Comparator supports comparison on null (natural ordering doesn’t allow null).
That’s all about differences between the HashSet and TreeSet in Java.
References:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)