1

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?

user3559471
  • 563
  • 2
  • 6
  • 17
  • 1
    Simple answer: when you need them to be different from the default implementation. Additional answer: in most cases you'll need to do that if the instances of that class should be put into a set or used as map keys. There are other situations, however, e.g. if you want two distinct instances to be considered equal if they have the same field values (in which case you'd override `equals()` and of course `hashCode()` due to what you already know: always override both or none). – Thomas Jun 30 '16 at 14:14

2 Answers2

1

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

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?!

GhostCat
  • 137,827
  • 25
  • 176
  • 248