How HashSet works with regards to hashCode()?

本秂侑毒 提交于 2019-12-03 13:32:28

If you look at the actual javacode of HashSet you can see what it does:

 // Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
...

 public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

So the element you are adding is the Key in the backing hashmap with a dummy value as the value. this dummy value is never actually used by the hashSet.

Your second question regarding overriding equals and hashcode:

It is really necessary to always override both if you want to override either one. This is because the contract for hashCode says equal objects must have the same hashcode. the default implementation of hashcode will give different values for each instance.

Therefore, if you override equals() but not hashcode() This could happen

object1.equals(object2) //true

MySet.add(object1);

MySet.contains(object2); //false but should be true if we overrode hashcode()

Since contains will use hashcode to find the bucket to search in we might get a different bucket back and not find the equal object.

If you look at the source for HashSet (the source comes with the JDK and is very informative), you will see that it creates an object to use as the value:

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

Each value that is added to the HashSet is used as a key to the backing HashMap with this PRESENT object as the value.

Regarding overriding equals() whenever you override hashCode() (and vice versa), it is very important that these two methods return consistent results. That is, they should agree with one another. For more details, see the book Effective Java by Josh Bloch.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!