If you look at the java 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;
}
Therefore, when you insert things into hashMap, hashCode hashMap will change. Thus, if we insert an empty hashMap into a hashSet, then insert something into this hash map, and then call it hashSet.contains(hashMap), it will return false. Why does Java allow this behavior? This will easily lead to duplication of elements in hashSet.
Try running 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());
}
}
}
}
source
share