Re: NetBeans awkward warning overriding hashCode
Joshua Cranmer wrote:
Ben Phillips wrote:
and then, in a subclass B, implement equalTo and hashCode (to be
consistent with one another), NetBeans warns of having overridden
hashCode without equals.
And why shouldn't it? There is no easy way to determine that equals has
"in effect" been overridden when you rely on auxiliary methods.
But it can, in principle, guess, based on if a method called by the
superclass equals has been overridden. It may, of course, guess wrong.
It can't be expected to detect every potential error, though; it
wouldn't warn if you override equals and hashCode but didn't make them
consistent (so, hashCode could return different values for distinct but
"equal" objects), for example.
With warnings, there's a balance to be struck between being too niggledy
and letting probable errors escape unnoticed. As a rule, something
"suspicious" should be flagged, but also should be overridable.
In this case, it turns out that using a "dummy"
punt-to-subclass-implementation of hashCode, even where the superclass
gives it no behavior of its own, does the trick (and the performance
penalty probably goes away once the JIT has hit that part of the code).
If the abstract superclass has some hash-influencing state of its own,
this becomes more "natural":
public boolean equals (Object o) {
if (o == this) return true;
if (o == null) return false;
if (!o instanceOf MyClass) return false;
MyClass foo = (MyClass)o;
if (!foo.member.equals(member)) return false;
return subclassEquals(foo);
}
public int hashCode () {
return member.hashCode()*17 + subclassHashCode();
}