File: NonOverridingEquals.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (39 lines) | stat: -rw-r--r-- 1,397 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Defining a method that looks like `Object#equals` but doesn't actually override
`Object#equals` is dangerous. The result of the comparison could differ
depending on the declared type of the argument passed into the `equals` call.

For example, consider this code:

```java
public class Example {
  private int value;

  public Example(int value) {
    this.value = value;
  }

  public boolean equals(Example other) {
    return this.value == other.value;
  }

  public static void main(String[] args) {
    Example exampleA = new Example(1);
    Example exampleB = new Example(1);
    System.out.println(exampleA.equals(exampleB));
  }
}
```

This will print `true`. Suppose you refactor it so that the variable `exampleB`
is declared as an `Object` instead. Now this code will print `false`, because
Java's overload resolution will choose the default `equals(Object)`
implementation instead of the `equals(Example)` method defined in this class.

If this equals method is intended to be a type-specific helper for an `equals`
method that *does* override `Object#equals`, either inline it into the
overriding `equals` method or rename it to something other than `equals` to
avoid ambiguity in overload resolution.

If you don't want to write and maintain `equals` and `hashCode` methods by hand,
consider rewriting this class to use
[AutoValue](https://github.com/google/auto/tree/master/value).