It says in the contract for the Comparator interface, that it must be consistent with equals.
That's not entirely correct; see @popovitjs' answer.
Does this mean that Comparator = zero if equalsTo = true , or does it mean that Comparator = zero if and only if equalsTo = true?
It means the latter. However, it is not actually a hard requirement for Comparator
objects.
I seem to remember that it is the second one, but I have come across lots of comparators which sort by non-unique sub properties.
Well that's reasonable, given that it is not actually a hard requirement. In fact, a Comparator
that is inconsistent with equals(Object)
is just fine if you are going to use it with Arrays.sort(...)
. The problems only arise with TreeSet
and TreeMap
.
For example, suppose that you have a Comparator<E> C
that says e1
and e2
are not equal, but e1.equals(e2)
returns true
. Now suppose that you create a TreeSet<E>
instance using the comparator, and then add e1
and e2
to that set. The set's tree is organized based on the comparator, and therefore e1
and e2
will slot into different places in the search tree, and will both be elements of the set. But that violates the primary invariant of a Set
... which is based on the equals
method.
As the javadoc for TreeSet
says:
"Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface."
And this answers the last part of your question.
What are the consequences for this type of violation?
If you use an inconsistent Comparator in a TreeSet or TreeMap, the collection will not obey the Set
or Map
contract.