Re: do I need to override the equals() method?
Mike Schilling wrote:
Patricia Shanahan wrote:
Mike Schilling wrote:
It occurs to me that something I'd like in an IDE is for it to let
me mark the fields that consititute my unique key, and then it can
generate equals() and hashCode() . The process is mechanical
enough
for the result to be at least 90% correct.
Eclipse has a hashCode and equals builder. It brings up a dialog
that
lists the local variables with check boxes, and also gives an option
to use either instanceof or class object identity to test for class
equality.
Very nice. I see that IntelliJ has it too, now that I think to look.
I like the fact that it deals with the two methods together, and
that
you only get to pick variables once for both methods, reducing the
risk of inconsistent equals and hashCode.
IntelliJ lets you choose the fields for equals() and then optionally
choose only a subset for hashCode(). That's logically correct; I'm
not sure when I'd use that flexibility, though.
NetBeans has this feature also. Alt-Insert, "equals() and hashCode()",
checkbox the desired fields, shows side by side the checkboxes for each method
so you can do what Mike likes.
For a class 'Foonteger' with a single 'BigInteger' field 'value' (checkbox
checked) it inserted:
--------------------------------
@Override
public boolean equals( Object obj )
{
if ( obj == null )
{
return false;
}
if ( getClass() != obj.getClass() )
{
return false;
}
final Foonteger other = (Foonteger) obj;
if ( this.value != other.value &&
(this.value == null || !this.value.equals( other.value )) )
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int hash = 7;
return hash;
}
--------------------------------
Not my favorite implementation, but sufficient.
--
Lew