In Java, the Object.equals()
method is used for object comparison, and it is typically overridden in classes to provide a custom
equality check based on your criteria for equality.
The default implementation of equals()
provided by the Object
class compares the memory references of the two objects,
that means it checks if the objects are actually the same instance in memory.
The "equals" as a method name should be used exclusively to override Object.equals(Object)
to prevent confusion.
It is important to note that when you override equals()
, you should also override the hashCode()
method to maintain the
contract between equals()
and hashCode()
.
Either override Object.equals(Object)
or rename the method.
class MyClass { private int foo = 1; public boolean equals(MyClass o) { // Noncompliant; does not override Object.equals(Object) return o != null && o.foo == this.foo; } public static void main(String[] args) { MyClass o1 = new MyClass(); Object o2 = new MyClass(); System.out.println(o1.equals(o2)); // Prints "false" because o2 an Object not a MyClass } }
class MyClass { private int foo = 1; @Override public boolean equals(Object o) { // Compliant if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MyClass other = (MyClass)o; return this.foo == other.foo; } }