Sub topic 1
Object: where equals, hashCode, and toString come from
Every Java object can be compared, hashed, and printed, even if its class says nothing about any of those things. This works because all classes inherit three methods from java.lang.Object. This chapter shows where those methods come from and what they do by default. It also explains why the defaults are rarely what you want for a class that represents a value.
Prerequisites
This chapter assumes you can already do the following:
- Write and compile a Java class with fields and constructors.
- Tell a primitive value from an object reference.
- Use
List,Set, andMapfromjava.utilat a basic level. - Read and write method overrides, including the
@Overrideannotation.
Object is the root of every class
If you declare a class without an extends clause, the compiler treats it as if you had written extends Object. If you extend another class, that class's chain of parents eventually ends at Object. Every class therefore has exactly one path to Object, and every class inherits its public and protected methods.
Three more things follow from this rule:
- Interfaces do not extend
Object, but a variable of an interface type can still callequals,hashCode, andtoString. The language guarantees that any object behind the reference is anObject. - Arrays are objects. They inherit the three methods from
Objectwithout changing them. - Enums and records are classes too. Enums fix their
equalsandhashCodeto identity behavior. Records generate value-based versions, which a later chapter covers.
What Object provides
Object declares a small set of methods. Three are the subject of this tutorial, and the others are context.
| Method | Signature | Default behavior |
|---|---|---|
| `equals` | `boolean equals(Object obj)` | Returns `true` only if `this == obj` (same reference). |
| `hashCode` | `int hashCode()` | Returns an identity-based integer assigned by the JVM. |
| `toString` | `String toString()` | Returns `getClass().getName() + "@" + Integer.toHexString(hashCode())`. |
| `getClass` | `final Class<?> getClass()` | Returns the runtime class. You cannot override it. |
| `clone` | `protected Object clone()` | Makes a shallow copy if the class implements `Cloneable`. |
| `wait`, `notify`, `notifyAll` | `final` methods | Thread coordination on the object's monitor. |
| `finalize` | `protected void finalize()` | Deprecated for removal. Do not use it. |
Only equals, hashCode, and toString are meant to be overridden routinely. The signatures matter. In particular, equals takes an Object, not your own class. A later chapter shows the bug that appears when you get this wrong.
Seeing the defaults
The following program uses a class that overrides nothing. Each line shows one default behavior.
public class DefaultsDemo {
static class Widget {}
public static void main(String[] args) {
Widget a = new Widget();
Widget b = new Widget();
System.out.println(a.equals(a)); // true: same reference
System.out.println(a.equals(b)); // false: different objects
System.out.println(a.hashCode() == System.identityHashCode(a)); // true
System.out.println(a); // DefaultsDemo$Widget@ followed by hex digits
String manual = a.getClass().getName() + "@" + Integer.toHexString(a.hashCode());
System.out.println(manual.equals(a.toString())); // true
}
}The hex digits in the printed line differ from run to run and from machine to machine. Do not write code or tests that depend on them. The $ in DefaultsDemo$Widget is how the JVM names a nested class.
The default hashCode is not a memory address
A common belief is that the default hash code is the object's memory address. It is not. HotSpot, the common JVM, generates the value on first use and stores it in the object's header. The JVM may move objects during garbage collection, so a memory address could not stay stable. The identity hash stays the same for the life of the object.
Two consequences follow:
- Two distinct objects can have the same identity hash. The value is only 31 or so bits wide, and the JVM does not promise uniqueness. So you cannot use
hashCode()as an identity check. System.identityHashCode(obj)always returns the identity-based value, even for a class that overrideshashCode. It is useful when you want to see the default value anyway.
Why the defaults are not enough
The defaults treat every object as unique. That is correct for things that really are unique, such as a Thread, a database connection, or a file handle. Two threads are never "the same thread" because they hold equal data.
For value-like classes, the defaults give the wrong answer. Suppose a Point class holds two ints. Most programs expect two points with the same coordinates to be interchangeable. With the inherited equals, they are not. A List<Point> will not find a point by value, and a HashSet<Point> will happily store duplicates.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ValueTrouble {
static class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}
public static void main(String[] args) {
List<Point> list = new ArrayList<>();
list.add(new Point(1, 2));
System.out.println(list.contains(new Point(1, 2))); // false
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
set.add(new Point(1, 2));
System.out.println(set.size()); // 2, not 1
System.out.println(new Point(1, 2)); // ValueTrouble$Point@ and hex digits
}
}Three symptoms appear. contains fails, the set keeps duplicates, and printing tells you nothing about the contents. The fix for each symptom is a different override, and the chapters that follow build them one at a time.
Where these methods are called for you
Many of the calls to these methods are implicit. You will not see equals or toString in your source, yet they run.
| Code you write | Method the runtime calls |
|---|---|
| `"Point: " + p` | `p.toString()` (through `String.valueOf`) |
| `System.out.println(p)` | `String.valueOf(p)`, which calls `p.toString()` |
| `list.contains(p)`, `list.indexOf(p)`, `list.remove(p)` | `equals` on elements |
| `set.add(p)`, `map.put(p, v)`, `map.get(p)` | `hashCode`, then `equals` |
| `Objects.equals(a, b)` | `a.equals(b)` after null checks |
| `assertEquals(expected, actual)` in JUnit | `expected.equals(actual)` |
Because the collections call these methods behind your back, a mistake in an override shows up far from the class that contains it. A broken hashCode appears as a HashMap that "loses" entries, not as an exception in the class itself.
Edge cases to know now
Arrays keep the defaults
Arrays inherit Object's identity-based methods. Calling equals or toString on an array rarely gives useful results. Use the java.util.Arrays helpers instead.
import java.util.Arrays;
public class ArrayDefaults {
public static void main(String[] args) {
int[] x = {1, 2, 3};
int[] y = {1, 2, 3};
System.out.println(x.equals(y)); // false: identity comparison
System.out.println(Arrays.equals(x, y)); // true: element-wise
System.out.println(x); // [I@ followed by hex digits
System.out.println(Arrays.toString(x)); // [1, 2, 3]
}
}The prefix [I is the JVM's name for the class int[].
Calling a method on null
Calling p.equals(q), p.hashCode(), or p.toString() when p is null throws a NullPointerException. The static helpers Objects.equals(a, b), Objects.hashCode(o), and Objects.toString(o) accept null and return sensible results. String concatenation and String.valueOf(Object) print "null" for a null reference.
Many JDK classes already override these methods
String, the wrapper classes such as Integer, List, Set, Map, LocalDate, and BigDecimal all override the three methods with value-based versions. That is why new String("a").equals("a") is true and why a List prints as [1, 2, 3]. The classes you write do not get this behavior unless you add it.
Overriding is a promise, not just a feature
Object documents rules, called contracts, for equals and hashCode. Collections, caches, and test frameworks all assume your override follows them. A class that breaks the rules compiles and often seems to work in small tests. It then fails with wrong results rather than errors. The next chapters state the rules exactly.
Exercise
A class Session does not override any method of Object. You run Session s1 = new Session(); Session s2 = s1; and then compare s1.equals(s2) and new Session().equals(s1). What do the two calls return, and why?
Show answer
The first call returns true because s1 and s2 refer to the same object, and the inherited equals is the same as ==. The second call returns false because it compares a different new object with s1, so the references differ.
Exercise
A teammate says that two objects with the same hashCode() value must be equal, and that you can use the default hashCode() to check whether two references point to the same object. Explain what is wrong with both statements.
Show answer
Equal hash codes do not imply equal objects, because different objects can share a hash code (a collision). The default hash code is an identity-based value that the JVM does not guarantee to be unique, so two distinct objects can return the same number. To check for the same object, use ==.
Exercise
What does System.out.println(new int[] {1, 2}) print, and what should you call to print [1, 2] instead?
Show answer
It prints the default Object.toString form for an array, which is [I@ followed by hex digits that vary. Print Arrays.toString(array) to get [1, 2].