File: InconsistentHashCode.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 (34 lines) | stat: -rw-r--r-- 828 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
Implementations of `Object#hashCode` should not incorporate fields which the
implementation of `Object#equals` does not. This violates the contract of
`hashCode`: specifically, equal objects must have equal hashCodes.

```java
class Foo {
  private final int a;
  private final int b;

  Foo(int a, int b) {
    this.a = a;
    this.b = b;
  }

  @Override
  public boolean equals(@Nullable Object o) {
    return o instanceof Foo && ((Foo) o).a == a;
  }

  @Override
  public int hashCode() {
    return a + 31 * b;
  }
}

Foo first = new Foo(10, 20);
Foo second = new Foo(10, 40);

first.equals(second) // true
first.hashCode() == second.hashCode() // false
```

The fix for this class is either to include a comparison of `b` in the `#equals`
method, or remove `b` from `#hashCode`. The former is more likely to be correct.