Re: Sort Map on Value
Wojtek wrote:
Lew wrote :
The documentation for 'SortedMap' and 'TreeMap' very distinctly warns
that the implementations use 'compare' and 'compareTo' instead of
'equals', and very strongly advise that one keep the methods
consistent.
the equals() uses a compareTo() internally, that would be against the
key:
That does not pertain to what I'm saying. I'm discussing the use of
'compareTo' instead of 'equals', not by 'equals'.
@Override
public boolean equals( Object key )
{
return ivKey.equals( ((PersonMapKey) key).getKey() );
}
That's all well and good, but your 'equals' is not consistent with
your implementation of 'compareTo', and therefore could raise trouble
for SortedMap implementations, according to the Javadocs.
Ok, so why is it that the interface Comparable does not also have
public boolean equals(Object o);
as part of its definition?
If you do something different inside compareTo(), then that difference
should be reflected in equals() should it not?
Since Object itself defines equals(), every descendant of Object
has an equals() method, either its own or something it inherited.
So adding equals() to an interface would accomplish nothing; every
class already has an equals() and the requirements of the interface
are satisfied.
The only reason I can think of to put equals() or hashCode() or
toString() into an interface definition is if you wanted to hang some
special Javadoc on them: "Every class implementing this interface should
provide a toString() method that rot13's its output" or some such.
Still, it would have no "prescriptive" value that the compiler could
know of and enforce.
... which gets to a more general point: Interfaces and abstract
classes can require subclasses to implement certain methods, but they
really can't control what the methods do. There's a "general contract"
that equals() and hashCode() should be consistent, but there's no way
for the compiler to enforce the consistency; the contract is written
in Javadoc, not in Java. Similarly for compareTo(): The understanding
is that it should be consistent with equals(), that it should have
nice properties like transitivity, and so on -- but the compiler is
not in a position to detect breaches of this Javadoc-not-Java contract.
The compiler can check that you have a method of the right name, the
right parameter list, the right return type, and the right access, but
it can't tell a "good faith" implementation from a silly one.
--
Eric.Sosman@sun.com