Default Object hashCode and Identity
What you'll learn: How Java's Object class provides a default hashCode() implementation based on object identity, making every instance unique by default.
The Default Behavior
When you create a class in Java without overriding hashCode(), you inherit the implementation from Object. This default hashCode() is identity-based—it typically returns a value derived from the object's memory address. This means two objects are considered different for hashing purposes even if they have identical field values.
Why This Matters for Collections
Think of it like this: imagine a library where every book is tracked by its physical location on the shelf, not by its title or content. Two copies of the same book would be treated as completely different items because they occupy different shelf positions.
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Using default Object hashCode
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Alice", 30);
System.out.println(p1.hashCode()); // e.g., 366712642
System.out.println(p2.hashCode()); // e.g., 1829164700 (different!)
System.out.println(p1.equals(p2)); // false (default Object equals uses ==)
Even though p1 and p2 have identical data, they produce different hash codes because they're different objects in memory. If you add both to a HashSet, both will be stored as separate elements—likely not what you want for a "Person" concept.
This identity-based approach is Java's safe default: it guarantees uniqueness per instance, but it won't work correctly for value-based equality scenarios.
Key Takeaway: The default Object.hashCode() is identity-based, treating each instance as unique regardless of field values—you must override both hashCode() and equals() to achieve value-based equality in collections.