JavaIntermediate#object#hashmap

What is the purpose of the hashCode() method and its contract with equals()?

hashCode() returns an integer used by hash-based collections (HashMap, HashSet) to bucket objects. The contract states equal objects must have equal hash codes; violating this breaks hash collection behavior even if equals() is correct.

Example
class Point {
  int x, y;
  public boolean equals(Object o) { /* compare x,y */ return true; }
  public int hashCode() { return Objects.hash(x, y); } // must be consistent with equals
}

Related Questions

1
JavaBeginner#fundamentals

What is the instanceof operator?

Open
2
JavaBeginner#fundamentals#java10

What is the difference between var and explicit typing in Java 10+?

Open
3
JavaIntermediate#inner-classes

What is the difference between a static nested class and a non-static inner class?

Open