I have a Hashmap which has X number of elements
I need to move this map into another map
This is what my code looks like
Map originMap = initialize();
Map destMap = new Hashmap ();
int originMapSize = originMap.size();
Set<Map.Entry<K, V>> entries = originMap.entrySet();
for (Map.Entry<K, Y> mapEntry : entries) {
K key = mapEntry.getKey();
V value = mapEntry.getValue();
destMap.put (key,value);
}
// Shouldnt this be equal to originMapSize ????
int destMapSize = destMap.size();
What I am observing is – originMapSize is NOT equal to the destMapSize
It seems when we put the elements in the destMap, some of the elements are being overridden
We have overrridden the hashCode and equals method- and it is a suspicious implementation.
However, if the originMap allowed the elements to be added, why would the destinationMap not add a new elements and override an existing element instead ?
This could happen if the
equalsmethod was asymmetric. Suppose there are two keys a and b such that:a.hashCode() == b.hashCode()a.equals(b)returns falseb.equals(a)returns trueThen suppose that the
HashMapimplementation searches for an existing key by callingexistingKey.equals(newKey)for each existing key with the same hash code as the new key.Now suppose we originally add them in the order { a, b }.
The first key (
a) obviously goes in with no problems. The second key (b) insertion ends up callinga.equals(b)– which is false, so we get two keys.Now building the second
HashMap, we may end up getting the entries in the order { b, a }.This time we add
bfirst, which is fine… but when we insert the second key (a) we end up callingb.equals(a), which returns true, so we overwrite the entry.That may not be what’s going on, but it could explain things – and shows the dangers of an asymmetric
equalsmethod.EDIT: Here’s a short but complete program demonstrating this situation. (The exact details of
aandbmay not be the same, but the asymmetry is.)Output on my machine:
You may not get the output that way round – it depends on:
equalsis called (candidateKey.equals(newKey)or vice versa)It may even work differently on different runs.