Re: do I need to override the equals() method?
- From: Patricia Shanahan <pats@xxxxxxx>
- Date: Fri, 03 Apr 2009 20:00:50 -0700
Mike Schilling wrote:
"Lew" <noone@xxxxxxxxxxxxx> wrote in message news:gr546m$s00$1@xxxxxxxxxxxxxxxxxxxxJoshua Bloch covers this in /Effective Java/, a book you must own.
Always override 'equals()' and 'hashCode()' together if at all. Make sure they are consistent with each other, i.e., if two instances compare equal, they must have the same hash code. (The converse is not true.) Make sure you involve each field that logically affects value equality.
For example, in comparing instances of a hypothetical 'Person' class, you might involve 'nationalID' (e.g., Social Security number). Or you might compare a combination of 'birthName', 'birthDate', 'birthPlace', 'birthGender' and 'disambiguator'. The same field(s) would be involved in both the 'equals()' and 'hashCode()' methods.
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.
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.
Patricia
.
- Follow-Ups:
- Re: do I need to override the equals() method?
- From: Mike Schilling
- Re: do I need to override the equals() method?
- References:
- do I need to override the equals() method?
- From: Marteno Rodia
- Re: do I need to override the equals() method?
- From: Albert
- Re: do I need to override the equals() method?
- From: Lew
- Re: do I need to override the equals() method?
- From: Mike Schilling
- do I need to override the equals() method?
- Prev by Date: Re: do I need to override the equals() method?
- Next by Date: Re: do I need to override the equals() method?
- Previous by thread: Re: do I need to override the equals() method?
- Next by thread: Re: do I need to override the equals() method?
- Index(es):
Relevant Pages
|