Java SE API
Java Object.hashCode()
Returns a hash value. Equal objects must have equal hash codes; unequal objects need not have different codes. Override consistently with equals when defining value equality.
Formal Syntax & Structure
java syntaxjava
public int hashCode()Return Value
int
Hash value consistent with equals.
Working Example
Example Snippetjava
final class GridCell { private final int row; private final int column; GridCell(int row, int column) { if (row < 0 || row > 999 || column < 0 || column > 999) throw new IllegalArgumentException("cell outside grid"); this.row = row; this.column = column; } public int row() { return row; } public int column() { return column; } public GridCell nextColumn() { return new GridCell(row, column + 1); } @Override public boolean equals(Object other) { if (!(other instanceof GridCell cell)) return false; return row == cell.row && column == cell.column; } @Override public int hashCode() { return 1000 * row + column; }}public class Main { public static void main(String[] args) { GridCell a = new GridCell(3, 5); GridCell b = new GridCell(3, 5); System.out.println(a == b); System.out.println(a.equals(b)); System.out.println(a.hashCode() == b.hashCode()); System.out.println(a.equals(null)); }}