Re: Sort Map on Value
Wojtek wrote:
Well the compareTo() is from the interface, the hashCode() and equals()
are overriding Object methods.
You keep saying "the" interface as if only one were involved.
Lew wrote:
I asked because the 'SortedMap' and 'TreeMap' documentation is very
strident about keeping 'compareTo()' and 'equals()' consistent with
each other, or else the map "just fails to obey the general contract
of the Map interface."
Wojtek wrote:
I know I am breaking some rules to force sorting on the Value, yet
lookup on the key. BTW, the tests I have done show that this works.
I figured you had tested it, nevertheless the warnings in the
documentation for 'SortedMap' and its implementations raise a concern
that there may be corner cases that your approach would break in those
types.
The code sample of a hash map I saw uses hashCode() and equals() to
This isn't about HashMap but TreeMap. Map and HashMap Javadocs don't
discuss keeping 'compareTo' consistent with 'equals'.
place and retrieve objects with no mention of compareTo(). And even if
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.
That said, the documentation also says that a SortedMap can work this
way, just that you are breaking aspects of the Map contract.
Unfortunately they give no indication of exactly what sort of bugs you
might expect from this.
I would not be comfortable with the hack that you suggest.
--
Lew