I know there are multiple blogs on "how to override equals and hashcode" and "problem if we override one not other".
My question is very simple. In what all situation it is suggested to override equals and hashcode?
I know there are multiple blogs on "how to override equals and hashcode" and "problem if we override one not other".
My question is very simple. In what all situation it is suggested to override equals and hashcode?
Do it whenever you need to override the default notion of equality: that two objects are equal only if they are the same object.
In other words, when two different instances can, in some sense, be "equal".
For example, Integer
overrides equals
because new Integer(2) != new Integer(2)
, but you'd expect new Integer(2).equals(new Integer(2))
. Intuitively, an object representing 2
should be equal to another object representing 2
.
You need to override hashCode
at the same time, in order that your value will work consistently with the equal
implementation in hash-based data structures.
I am pretty sure that most tutorials that explain how to do it ... also say why to you might have to do override those methods.
Anyway, the main reason to do that: if your class contains various fields, and you want to make sure that two objects of your class that have "same" content ... end up as equal.
So, the place where you care about equals/hashCode most often is when you start pushing your objects into collections for example.
Like:
public class Example {
private final String someId;
Example(String incoming) { someId = incoming };
Then:
new Example(new String("1")).equals(new Example(new String("1))
What is the thing you expect to come out of that?!