Normally with a Set
, the uniqueness of the contained objects is determined by their equals()
method. In your example, you would implement Car.equals()
such that two Cars would be equal if they had the same number, modelYear and horsePower. Then you could add your Corvette into the set and it wouldn't conflict with another model that has the same horsepower.
TreeSet
is different: it determines that two objects are identical, not when equals()
returns true
, but when the compareTo()
returns 0. This means you can easily find yourself with two objects that the TreeSet treats as identical, even though they aren't.
Indeed the doc for TreeSet
states:
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.
In other words, to not break the Set contract, TreeSet depends on YOU only ever supplying a Comparator
that's consistent with the equals()
implementation of the objects you put in the set.
Since TreeSet allows you to specify an arbitrary Comparator
, we might as well be more succinct and say that TreeSet breaks the Set contract.