简体   繁体   中英

Is it necessary to override hashcode method in non hashed datastructure

What I understand from hashcode method for objects in Java: it is required to calculate the hashcode of objects which in turn is used to calculate the index / bucket location of the object in a hashed datastructure like hashMap.

So will it be correct to say that for a class that is not to be used along with a hashed datastructure doesnt need to have hashCode() method implemented in it? in other words is overriding the equals() method enough for non hashed datastructures?

Also please correct me if my assumption is wrong.

In theory, you are correct: if you know that your object will never be used in any way that requires the hash code, then not implementing hashCode will not cause anything bad to happen.

In practice there are reasons not to rely on this fact:

  1. code changes and an objects that were initially planned to only ever exist in non-hashed structures get put into sets or used as the key to maps, because requirements change. If you don't implement hashCode then, things can go bad.
  2. if you implement equals and you don't implement hashCode then you are almost certainly breaking the contract of hashCode that requires it to be consistent to equals . If your code breaks a contract that other code depends on, then that other code can silently fail in unexpected/weird ways.
  3. in order to avoid mistakes it's usually best to let your IDE generate equals anyway and if you do that generating the appropriate hashCode at the same time is no extra effort.

Note that all of this assumes you even want to implement equals : If you don't care about equality of an object entirely (which is actually very common, not every type needs a specific equality definition), then you can just leave equals and hashCode out of your code and it's all conforming ('though your type might not match the "intuitive" equality definition of your type then).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM