Junior — Middle
How can an object be used as a key in a data structure?
sobes.tech AI
Answer from AI
In Java, an object can be used as a key in data structures such as HashMap or HashSet. To ensure proper functioning of the key, it is necessary to correctly override the equals() and hashCode() methods.
Why is this important:
hashCode()determines in which bucket the object will be stored.equals()checks whether two keys are equal.
If these methods are not overridden, the default implementation from the Object class is used, which compares objects by reference, which is not always suitable.
Example:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = 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 && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
// Usage in HashMap
Map<Person, String> map = new HashMap<>();
map.put(new Person("Alice", 30), "Developer");
String profession = map.get(new Person("Alice", 30)); // Will return "Developer"
Thus, to use an object as a key, it is necessary to ensure a correct implementation of equals() and hashCode().