Junior — Middle
What methods or properties need to be changed in an object to use it as a key in HashMap?
sobes.tech AI
Answer from AI
To use an object as a key in a HashMap, it is necessary to override the equals() and hashCode() methods.
hashCode()should return an integer value that corresponds to the hash code of the object. Objects that are equal according toequals()should have the samehashCode().equals()should correctly compare objects for equality based on your class's logic.
Example:
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() {
return Objects.hash(name, age);
}
}
Without the correct implementation of these methods, HashMap may not work correctly, for example, it may not find keys or may create duplicates.