A lot of answers have been given, based on technical considerations, especially around performance.
According to me, choice between TreeSet
and HashSet
matters.
But I would rather say the choice should be driven by conceptual considerations first.
If, for the objects your need to manipulate, a natural ordering does not make sense, then do not use TreeSet
.
It is a sorted set, since it implements SortedSet
. So it means you need to override function compareTo
, which should be consistent with what returns function equals
. For example if you have a set of objects of a class called Student, then I do not think a TreeSet
would make sense, since there is no natural ordering between students. You can order them by their average grade, okay, but this is not a "natural ordering". Function compareTo
would return 0 not only when two objects represent the same student, but also when two different students have the same grade. For the second case, equals
would return false (unless you decide to make the latter return true when two different students have the same grade, which would make equals
function have a misleading meaning, not to say a wrong meaning.)
Please note this consistency between equals
and compareTo
is optional, but strongly recommended. Otherwise the contract of interface Set
is broken, making your code misleading to other people, thus also possibly leading to unexpected behavior.
This link might be a good source of information regarding this question.