Potential traps when ignoring some fields in equals / hashCode?

If only some of the fields of the object represent the actual state, I believe that they can be ignored when overriding equals and hashCode ...

I feel awkward about this, although I wanted to ask,

  • Is this a common practice?
  • Are there any potential issues with this approach?
  • Is there any documentation or recommendations when ignoring some fields in equals / hashCode ?

In my specific situation, I study the state of the problem space. I would like to keep a hash of the states visited, but I am also considering including a path leading to the state. Obviously, the two states are equal, although they occur in different ways.

+6
source share
3 answers

This is based on how you consider the uniqueness of this object. If he has a primary key (a unique key), then just use this attribute.

If you think that uniqueness is a combination of 10 different attributes, then use all 10 attributes equally.

Then use only the attributes that you used as equals to generate the hash code, because the same objects must generate the same hash codes.

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

  • Is this a common practice? Yes

  • Are there any potential issues with this approach? Not

  • Is there any documentation or recommendations when ignoring some fields in equals / hashCode?

    "The equals method for the Object class implements the most discriminatory possible relation of equivalence to objects;

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

+3
source

Ultimately, "equals" means what you want it to mean. There is a limitation on the fact that "equal" values ​​must return the same hash code, and, of course, if two identical addresses "equal" must return true. But you could, for example, have “peers” that compared the contents of two web pages (ignoring the repeatability problem for nonce), and even though the URLs were different, “equal” if the page content matched some path .

+2
source

The best documentation / guidelines I've seen for overriding methods on Object was in Josh Bloch Effective Java . It has a whole chapter entitled “Methods common to all objects,” which includes the sections “Listen to the general contract when redefining peers” and “Always redefine the hash code when redefining peers”. It details the things you should consider when overriding these two methods. I will not answer directly; The book is definitely worth the cost for every Java developer.

0
source

Source: https://habr.com/ru/post/899547/


All Articles