Java SE API
Java Object.equals(Object)
Tests logical equality under the implementation’s equality policy. Object’s default policy is identity. Overrides must maintain reflexivity, symmetry, transitivity, consistency and false for null; equal objects require equal hash codes.
Formal Syntax & Structure
java syntaxjava
public boolean equals(Object obj)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| obj | Object | The object to compare; may be null. |
Return Value
boolean
Whether the objects are equal under the implementation contract.
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)); }}