The reason why most use HashSet
is that the operations are (on average) O(1) instead of O(log n). If the set contains standard items you will not be "messing around with hash functions" as that has been done for you. If the set contains custom classes, you have to implement hashCode
to use HashSet
(although Effective Java shows how), but if you use a TreeSet
you have to make it Comparable
or supply a Comparator
. This can be a problem if the class does not have a particular order.
I have sometimes used TreeSet
(or actually TreeMap
) for very small sets/maps (< 10 items) although I have not checked to see if there is any real gain in doing so. For large sets the difference can be considerable.
Now if you need the sorted, then TreeSet
is appropriate, although even then if updates are frequent and the need for a sorted result is infrequent, sometimes copying the contents to a list or an array and sorting them can be faster.