而当你使用HashMap存储键值对时,有可能会遇到一个疑问。
下面举一个我遇到的问题:
Person是一个实体类(已经重写了equals和hashCode方法) ,这里的HashMap是官方的HashMap
Person p1 = new com.mj.set.Person(12,1.67f,"jack");
Person p2 = new com.mj.set.Person(12,1.67f,"jack");
java.util.Map<Object, Integer> map2 = new java.util.HashMap<>();
map2.put(p1,1);
map2.put(p2,2);
System.out.println(map2.size());
System.out.println(map2.containsKey(p1));
当你在主函数执行这段代码时,会发现结果为1,true。
而你可能会有这样的疑惑:你不是已经用p2覆盖了p1吗,为什么map2中还是包含p1?
作出解释:
你翻阅Java官方的HashMap你会发现,那个containsKey(K key)方法是通过传入hash(key);,以及key查找node是否为空,如果为空,则返回false, 否则返回true。
getNode方法
/**
* Implements Map.get and related methods.
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V