Re: equals and hascode
On 12/18/2010 6:04 AM, Aeris wrote:
mark jason wrote:
MyMatrix.java:1 MyMatrix inherits equals and uses Object.hashCode()
One of the (transitive) superclass of your class redefined ??void
equals(Object)?? but not ??int hashCode()??
This is potentially wrong because Java doc say ??o1.equals(o2) =>
o1.hashCode() == o2.hashCode()?? and can lead to strange behavior (bad sort
on generic algorithm, wrong result of equals, breaked HashMap or HashSet???)
A ??good?? implementation of equals is
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if (obj == null || !(obj instanceof MyClass)) {
return false;
}
return this.hashCode() == obj.hashCode();
}
This is "??good??" in the sense that it satisfies the requirement
that equals() agree with hashCode(), but it does so only in a trivial
sense. If this implementation were "??good enough??", then it could
have been a `final' method of the Object class -- but it's not, meaning
that other classes are expected to have their own ideas about equals(),
notions that take into account more information than this one does.
For example, imagine that Long used this implementation for
equals(). Then for any Long instance `val', there would be
4294967295 other Long instances `valx' such that
val1.equals(valx) && val1.longValue() != valx.longValue()
.... leading to interesting consequences like
HashMap<Long,String> map = new HashMap<Long,String>();
map.put(1L, "one");
map.put(0x100000000L, "four gig");
assert (map.size() == 1);
.... which many people would find surprising -- and disappointing.
--
Eric Sosman
esosman@ieee-dot-org.invalid