Junior — Middle
What changes need to be made to the data structure to support a composite key?
sobes.tech AI
Answer from AI
To support a composite key in a data structure, it is necessary to modify the key representation so that it can contain multiple fields. In Java, this is usually achieved by creating a separate class that combines all the key fields and overriding the equals() and hashCode() methods for correct comparison and hashing.
Example:
public class CompositeKey {
private String part1;
private int part2;
public CompositeKey(String part1, int part2) {
this.part1 = part1;
this.part2 = part2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CompositeKey that = (CompositeKey) o;
return part2 == that.part2 && Objects.equals(part1, that.part1);
}
@Override
public int hashCode() {
return Objects.hash(part1, part2);
}
}
Such a key can be used, for example, in HashMap<CompositeKey, Value> for correct storage and lookup by a composite key.