views:

56

answers:

3

Difference between HashSet and TreeSet?

A: 

TreeSet is ordered. RTFM

foret
+1  A: 

You should check the JavaDoc of both classes. They are different in various aspects.

As an example, ordering:

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

Tomas Narros
+1  A: 

Take a look at the Java Tutorials trail on Set Implementations, from which I quote:

HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but offers no ordering guarantees. If you need to use the operations in the SortedSet interface, or if value-ordered iteration is required, use TreeSet; otherwise, use HashSet. It's a fair bet that you'll end up using HashSet most of the time.

dogbane