No, no, and cannot be a specification. In addition, you misunderstood how TreeSet
uses its Comparator
.
From TreeSet Javadoc :
Note that the ordering supported by the set (regardless of the comparator) must be matched if it correctly implements the Set interface. (See Comparable or Comparator for an exact definition consistent with peers.) This is because the Set interface is defined in terms of the equality operation, but the TreeSet instance does all the element comparisons using compareTo (or compare), so the two elements that are considered equal by from this point of view, they are equal to this method. the behavior of the set is well defined, even if its ordering is incompatible with equals; it simply does not obey the general contract Set interface.
From comparable javadoc :
A natural ordering for a class C is called consistent with if and only if e1.compareTo (e2) == 0 has the same logical value as e1.equals (e2) for all e1 and e2 of class C. Note that null is not is an instance of any class, and e.compareTo (null) should NullPointerException, although e.equals (null) returns false.
From the javadoc Collection :
boolean contains (Object o)
Returns true if this collection contains the specified item. More formally returns true if and only if the collection contains at least one element e such that (o == null? E == null: o.equals (e)).
Therefore, by specification, there can be no class that implements the Collection<E>
interface and is completely dependent on some external object in the Comparator style for inserting objects. All collections should use the equals
method of the Object
class to check if the object has already been inserted.
bezmax
source share