Junior
How are hashCode() and equals() methods implemented in the Object class?
sobes.tech AI
Answer from AI
In the Object class, the methods hashCode() and equals() have default implementations:
hashCode(): Usually returns an integer representing the internal address of the object in memory (or a value derived from it). This guarantees that different objects, at least in most cases, will have different hash codes.
// Typical implementation of hashCode() in Object
public native int hashCode();
equals(): Compares two objects by reference (this == obj). This means the method returnstrueonly if both variables refer to the same object in memory.
// Implementation of equals() in Object
public boolean equals(Object obj) {
return (this == obj);
}
These basic implementations are fundamental and should be overridden in subclasses if object comparison based on their content (i.e., logical equality check) is required, not just by reference. When overriding equals(), it is mandatory to also override hashCode() so that the rule is maintained: if two objects are equal according to equals(), their hash codes returned by hashCode() must be the same. The converse is not true (different objects can have the same hash code).