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:

  1. HashSet and TreeSet are members of the Java Collections Framework and implements java.util.Set interface.
  2. They don’t permit any duplicates values.
  3. Implementations of HashSet and TreeSet are not synchronized.
  4. Both HashSet and TreeSet can be wrapped using the Collections.synchronizedSortedSet() method to make them thread-safe.
  5. The iterators returned by HashSet and TreeSet iterator methods are fail-fast. Fail-fast iterators throw ConcurrentModificationException if the set is modified after the iterator is created without using iterator’s remove() method.

Differences:

Now let’s discuss some of the major differences between HashSet and TreeSet implementations.

  1. HashSet internally uses a HashMap instance, whereas TreeSet implementation is based on a TreeMap.
  2. The iteration order of the HashSet is undefined, whereas elements of TreeSet are ordered using their natural ordering or according to the specified Comparator.
  3. The time taken by HashSet for the majority of common set operations such as add, remove, contains, etc., is constant, whereas TreeSet takes O(log(n)) time for these operations.
  4. HashSet allows a null value, whereas TreeSet supports 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:

1. HashSet – Javadoc SE 9

2. TreeSet – Javadoc SE 9