Difference between HashSet and TreeSet ?

HashSet does not store data in any Order while the TreeSet stores data in order. Also, you can elements of any type to the hash set while you can only add similar types of elements into a tree set. 

HashSet:
  1. Class offers constant time performance for the basic operations (add, remove, contains and size).
  2. It does not guarantee that the order of elements will remain constant over time
  3. Iteration performance depends on the initial capacity and the load factor of the HashSet.
  4. It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow.
TreeSet:
  1. Guarantees log(n) time cost for the basic operations (add, remove and contains)
  2. Guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via it's constructor)
  3. Doesn't offer any tuning parameters for iteration performance
  4. Offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc



Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email