HashSet vs TreeSet

Difference between HashSet and TreeSet

HashSet

TreeSet

1) HashSet stores the element in random order .S0 there is no guarantee that the elements are print in which they are insert into HashSet . TreeSet elements are sorted in ascending order by default.
2) HashSet can store null object. TreeSet does not store null object. If one try to store null object in TreeSet object , it will throw Null Pointer Exception.
3)HashSet is much faster than TreeSet .  TreeSet is slower than HashSet.
4)HashSet is backed by HashMap.  TreeSet is backed by TreeMap .
5)HashSet offers constant time performance for the basic operations (add, remove, contains and size). TreeSet offers log(n) time cost for such operations.
6) HashSet uses equals() method for comparison .  TreeSet uses compareTo() method for maintaining ordering .

 

Similarities between HashSet and TreeSet

1) Both HashSet and TreeSet does not store duplicate elements.

2) Both of these classes are non-synchronized that means they are not thread-safe or multiple threads are access at same time .

3)Both HashSet and TreeSet uses shallow copy technique to create a clone of  their objects .

One thought on “HashSet vs TreeSet

Leave a comment