All entries for Wednesday 05 April 2006
April 05, 2006
Crappy crappy SortedSet!!! Why oh why???
Writing about web page http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedSet.html
So, what is the contract for a set?:
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
So what is the contract for a SortedSet?:
A set that further guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements (see Comparable), or by a Comparator provided at sorted set creation time. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue of SortedMap.)
Simple, sets do not support duplicates, SortedSets add an order? Right? Yes, but SortedSets also utterly break the contract of Sets (or at least add a stupid restriction); it completely ignores equals and uses compareTo instead! Why!. The java doc kinda hints at this:
Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface 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 sorted set 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 sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
I took this to mean that if the two objects are equals, then compareTo must return 0, but not, it means if compareTo returns 0 then a SortedSet treats them as equal, even if equal returns false!!!!
Code to prove it:
class TestClass implements Comparable {
private final Integer id;
private final String s;
public TestClass(final Integer id, final String s) {
this.id = id;
this.s = s;
}
public int compareTo(final Object o) {
if (equals(o)) {
return 0;
}
return ((TestClass)o).s.compareTo(s);
}
public boolean equals(final Object o) {
return ((TestClass)o).id.equals(id);
}
}
public void testTheProblem() {
TestClass firstTestClass = new TestClass(1, "same string");
TestClass secondTestClass = new TestClass(2, "same string");
assertFalse("equality", firstTestClass.equals(secondTestClass));
assertTrue("comparison", firstTestClass.compareTo(secondTestClass) == 0);
SortedSet testClasses = new TreeSet();
assertTrue("adding first item", testClasses.add(firstTestClass));
// this fails!!!
assertTrue("adding second item", testClasses.add(secondTestClass));
}
Please wait - comments are loading
Loading…