How can AbstractMap.SimpleEntry be simultaneously
1) mutable (it's method setValue() changes value part of the entry)
2) having equals()/hashCode() defined including value part of the entry
3) be the part of Set<Map.Entry<T,K>> entrySet() result
It seems to me, that these three points are controversial. For example, first two violates contract of Set<> interface, which is not recommending to have mutable elements of the set.
May I be sure, that mutating of Value won't break the map?
Why didn't they did Entry comparable and hashable by key only? This would increase speed in some cases?
I be sure, that mutating of Value won't break the map?
Yes, absolutely. The HashMap buckets take into account only the key portion of the entry:
public V [More ...] put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode()); // <<== HERE
...
}
Why didn't they did Entry comparable and hashable by key only? This would increase speed in some cases?
The hashCode and equals of Map.Entry have very little relevance: they would be used only if you wanted to hash entries outside the HashMap itself. The internal implementation of the EntrySet supplied to the callers of Map.entrySet does not use hashCode / equals of the entry - instead, they use the hash code of only the key portion. Here is part of a relevant source code for looking up an object in the entry set:
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<K,V> e = (Map.Entry<K,V>) o;
Entry<K,V> candidate = getEntry(e.getKey());
return candidate != null && candidate.equals(e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With