The only solution I have now is to define some static Comparator in Person class and then, override an equals method in that way that it uses this comparator
Don't do that. Nothing in the Comparator
contract requires that two objects which are different with regards to .equals()
compare to non zero. The only constraint which can be placed is that if two objects are .equals()
then compared to one another they give 0. The implementation of Comparable
is then said to be "compatible with equals". But some classes don't even respect that in the JDK (see BigDecimal
).
You have two choices:
- Use a
SortedSet
. ATreeSet
for instance allows you to pass aComparator
at runtime. ASortedSet
evaluates equivalence to the fact that two instances compared to one another give 0, regardless of.equals()
. - If you use Guava, you can create one or more
Equivalence
s for your objects; yourSet
will then have to have members of typeEquivalence.Wrapper<Person>
instead of justPerson
and you'll have to.add(eq.wrap(person))
, but it works.