Sub topic 1
Object: where equals, hashCode, and toString come from
Prerequisites
You should know how to write basic Java classes, use constructors, and distinguish primitive values from object references. You should also know basic method overriding and the List, Set, and Map interfaces.
Object provides the methods
Every Java class extends java.lang.Object, either directly or indirectly. Object defines methods that every object has:
equals(Object)compares objects.hashCode()returns an integer used by hash-based collections.toString()returns a text representation.
The default equals method compares identity. Two references are equal only when they point to the same object. The default toString usually includes the class name and an identity-based value, so it is rarely useful for application output.
class User {
final String name;
User(String name) {
this.name = name;
}
}
User first = new User("Ada");
User second = new User("Ada");
System.out.println(first.equals(second)); // false
System.out.println(first.toString()); // User@...`==` versus `equals`: identity and equality
For object references, == asks whether two references point to the same object. equals asks whether the objects have the same logical value, but only if the class overrides it.
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // trueThe equals contract
A correct equals implementation is:
- Reflexive:
x.equals(x)is true. - Symmetric:
x.equals(y)andy.equals(x)agree. - Transitive: if
xequalsy, andyequalsz, thenxequalsz. - Consistent: repeated calls agree while relevant state is unchanged.
- False for
null.
Equal objects must also return equal hash codes. This rule lets HashSet and HashMap find logically equal objects.
Writing equals step by step
Compare identity first, reject null and unrelated types, then compare every field that defines the value. Use Objects.equals for nullable fields.
import java.util.Objects;
public final class User {
private final String name;
public User(String name) {
this.name = name;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof User)) return false;
User user = (User) other;
return Objects.equals(name, user.name);
}
}Use @Override; it catches accidental overloads such as equals(User). Add a matching hashCode before using the class as a collection key.
Exercise
Why can two separately created User("Ada") objects be equal even though == returns false?
Show answer
== compares references, while the overridden equals method compares their logical field values.