Search code examples
javasetcomparable

Interchanging HashSet and TreeSet


Possible Duplicate:
Hashset vs Treeset

Can you use HashSet and TreeSet interchangeably? If I exchanged TreeSet for Hashset and vice versa in a program what issues would there be? Im aware you need to implement Comparable for a TreeSet.


Solution

  • If some API requires Set, it absolutely doesn't matter which implementation you pass. If it requires concrete type (unlikely), you can't mix them.

    In general, they difference is in performance (HashSet is faster) but this shouldn't affect how your program behaves and in order. Order of items in HashSet is unpredictable. If your program relies on any such order, it should rather use LinkedHashSet or TreeSet.