Junior — Middle
What happens if you insert two keys with the same hash code but different equals values into a HashMap?
sobes.tech AI
Answer from AI
In Java, keys in a HashMap are stored in buckets indexed by their hash code. If two keys have the same hash code, they go into the same bucket, but their equality is determined by the equals method.
If you insert two keys with the same hash code but not equal according to equals, HashMap will store both as separate entries in the same bucket.
Example:
Map<Key, String> map = new HashMap<>();
Key key1 = new Key(1); // hashCode = 42
Key key2 = new Key(2); // hashCode = 42, but !key1.equals(key2)
map.put(key1, "value1");
map.put(key2, "value2");
System.out.println(map.size()); // 2
Thus, the same hash code does not mean the keys are equal. HashMap first finds the bucket by hash, then compares keys with equals. If equals returns false, the key is considered new and added.