Junior — Middle
How to implement a method for calculating a unique hash of an object in Java?
sobes.tech AI
Answer from AI
In Java, to compute a unique hash of an object, the hashCode() method is usually overridden. It is important that:
- If two objects are equal (
equals()returnstrue), their hashes should match. - A good hash should distribute values evenly to reduce collisions.
Example implementation for a Person class with name and age fields:
public class Person {
private String name;
private int age;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
}
This uses a simple formula with a multiplier of 31, which is widely used in Java for hash calculation.
You can also use Objects.hash() for simplification:
@Override
public int hashCode() {
return Objects.hash(name, age);
}