Junior
What is the purpose of the hashCode method?
sobes.tech AI
Answer from AI
The hashCode() method in Java and Kotlin is used to generate an integer value representing an object. It plays a key role in working with collections based on hash tables (HashMap, HashSet, Hashtable), where it is used for quick determination of the "bucket" in which the object should be located or searched for. Key points:
- Ensuring the
equalsandhashCodecontract: If two objects are considered "equal" by theequals()method, theirhashCode()should return the same value. The reverse is not true: different objects can have the same hash code (collision). - Fast search/insertion: The hash code is used as an index for quick access to elements in hash collections. Without it, search in large collections would be significantly slower.
- Optionality: If an object is not intended to be used as a key in hash collections, the default implementation of
hashCode()(usually based on memory address) may be sufficient. However, ifequals()is overridden,hashCode()should also be overridden to maintain the contract. - Stability: The
hashCode()value for an immutable object should remain unchanged throughout its lifetime. For mutable objects, the hash code may change, but this requires caution when used in hash collections.
Example of a basic implementation in Kotlin:
data class User(val id: Long, val name: String)
// For data classes, hashCode() and equals() are generated automatically
Example of a manual implementation in Java (important to correctly combine values):
class User {
private final long id;
private final String name;
public User(long id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
Objects.equals(name, user.name); // Using Objects.equals to avoid NullPointerException
}
@Override
public int hashCode() {
return Objects.hash(id, name); // Using Objects.hash to combine hash codes
}
}