Difference between HashSet and TreeSet in Java

  • HashSet is much faster than TreeSet but offers no ordering guarantees like TreeSet.
  • Class offers constant time performance for the basic operations (add, remove, contains and size).
  • It does not guarantee that the order of elements will remain constant over time
  • Iteration performance depends on the initial capacity and the load factor of the HashSet.
  • 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.
  • Guarantees log(n) time cost for the basic operations (add, remove and contains)
  • Guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via it's constructor)
  • TreeSet will not allow null object .if you try to add null value i will be throw null pointer exception
  • Doesn't offer any tuning parameters for iteration performance
    • offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc.
Important points:
  • Both Sets will not allow duplicate elements.
  • It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal.
  • HashSet and TreeSet are not synchronized. That is if multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.