Junior — Middle
Mis juhtub, kui HashMap-i sisestada kaks võtit sama hash-koodiga, kuid erinevate väärtustega vastavalt equals?
sobes.tech AI
Vastus AI-lt
In Java's HashMap, keys are stored in buckets indexed by the hash code. If two keys have the same hash code, they fall into the same bucket, but to determine uniqueness, the equals method is used.
If you insert two keys with the same hash code but which are not equal according to equals, HashMap will store both keys 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
Therefore, the same hash code does not mean the same keys. HashMap first searches in the bucket by hash, then compares keys using equals. If equals returns false, the key is considered new and added to the collection.