What does equals(Object obj) do?

It redefines “equality” of objects.

By default (defined in java.lang.Object), an object is equal to another object only if it is the same instance. But you can provide custom equality logic when you override it.

For example, java.lang.String defines equality by comparing the internal character array. That’s why:

String a = new String("a"); //but don't use that in programs, use simply: = "a"
String b = new String("a");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true

Even though you may not need to test for equality like that, classes that you use do. For example implementations of List.contains(..) and List.indexOf(..) use .equals(..).

Check the javadoc for the exact contract required by the equals(..) method.

In many cases when overriding equals(..) you also have to override hashCode() (using the same fields). That’s also specified in the javadoc.

Leave a Comment