If you look at java's hashCode method inside hashMap, you will find:
public int hashCode() {
int h = 0;
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext())
h += i.next().hashCode();
return h;
}
So when you insert things into hashMap, hashMap's hashCode will change. Thus, if we insert an empty hashMap into hashSet, then insert something to this hashMap, then call hashSet.contains(hashMap)
, it will return false
.
Why does Java allow such behavior? This will easily cause duplicate items in a hashSet.
Try run the following code:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashSet<HashMap<Integer, String>> set = new HashSet<>();
HashMap<Integer, String> b = new HashMap<>();
System.out.println("adding hashcode: " + b.hashCode() + "to set");
set.add(b);
b.put(8, "arsenal");
for(HashMap<Integer, String> map: set){
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
System.out.println("Finding b: " + set.contains(b));
System.out.println(b.hashCode());
set.add(b);
for(HashMap<Integer, String> map: set){
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
}
}