On Fri, 9 Jul 2010, Patricia Shanahan wrote:
On 7/9/2010 12:45 PM, Tom Anderson wrote:
On Thu, 8 Jul 2010, Eric Sosman wrote:
Or, you could have BigList implement List but "lie" in its .size()
method, in somewhat the same way TreeSet "lies" about the Set contract.
How does TreeSet lie about the Set contract?
The case I'm aware of involves a TreeSet with a Comparator, that is
not consistent with the .equals methods of the TreeSet elements. The
TreeSet always goes by the Comparator results. That means the TreeSet
could contain elements a and b such that a.equals(b).
True.
Though that feel more like "TreeSet requires its Comparator to be
consistent with equals" than "TreeSet lies about the Set contract".
If i write this:
class MakeAHashOfThings {
public int h;
public int hashCode() {
return h;
}
}
Set s = new HashSet();
MakeAHashOfThings o = new MakeAHashOfThings();
o.h = 1;
s.add(o);
o.h = 2;
s.add(o);
Is HashSet now breaking the Set contract?
A contract places obligations on both parties. The Set contract requires
the implementation not to contain multiple equal items. But the TreeSet
and HashSet contracts (and classes do constitute their own contracts,
which one must agree to in order to construct them) require the calling
code to use valid Comparators and hashCodes. If the calling code
violates the terms of the contract, then the whole thing is null and
void anyway.
with equals. TreeSet is perfectly usable given a Comparator that is
internally consistent, even if it is not consistent with equals.
is consistent with equals.".