Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Potential pitfalls when ignoring some fields in equals/hashCode?

If only some of the fields of an object represents the actual state, I suppose these could be ignored when overriding equals and hashCode...

I get an uneasy feeling about this though, and wanted to ask,

  1. Is this common practice?
  2. Are there any potential pitfalls with this approach?
  3. Is there any documentation or guidelines when it comes to ignoring some fields in equals / hashCode?

In my particular situation, I'm exploring a state-space of a problem. I'd like to keep a hash set of visited states, but I'm also considering including the path which lead to the state. Obviously, two states are equal, even though they are found through different paths.

like image 792
aioobe Avatar asked Oct 18 '11 18:10

aioobe


2 Answers

This is based on how you would consider the uniqueness of a given object. If it has a primary key ( unique key) , then using that attribute alone is enough.

If you think the uniqueness is combination of 10 different attributes, then use all 10 attributes in the equals.

Then use only the attributes that you used in equals to generate the hashcode because same objects should generate the same hashcodes.

Selecting the attribute(s) for equals and hashcode is how you define the uniqueness of a given object.

  • Is this common practice? Yes

  • Are there any potential pitfalls with this approach? No

  • Is there any documentation or guidelines when it comes to ignoring some fields in equals / hashCode?

    "The equals method for class Object implements the most discriminating possible equivalence relation on objects;"

This is from object class Javadoc. But as the author of the class , you know how the uniqueness is defined.

like image 149
java_mouse Avatar answered Oct 06 '22 09:10

java_mouse


Ultimately, "equals" means what you want it to mean. There is the restriction that "equal" values must return the same hashcode, and, of course, if presented with two identical address "equals" must return true. But you could, eg, have an "equals" that compared the contents of two web pages (ignoring the issue of repeatability for the nonce), and, even though the URLs were different, said "equal" if the page contents matched in some way.

like image 33
Hot Licks Avatar answered Oct 06 '22 09:10

Hot Licks