记住这个定理吧:
equal objects must have equal hash codes.
首先:java.lang.Object.hashCode() 是三条约定是
1、多次运行 hashCode(),其值必须总是一致的(前提:1、 equals() 中用到的信息没发生变化 2、在同一次 execution 中)
2、obj1.equals(obj2) == true,则必须 obj1.hashCode() == obj1.hashCode() 总是 true
3、obj1.equals(obj2) == false,则 obj1.hashCode() == obj1.hashCode() 最好 false
这是因为 HashMap.containsKey(),HashMap.put() 时
a:由于 hash 不同,则直接就不尝试了(好。这样效率高啊)
b:“两把刷子程序员” 把 hash 弄成相同的(equals()不同,hashCode()相同),还得向下尝试 equals() (不好)
像我这种心细的 2B 青年,肯定会问(既然 equals() 对 hashCode() 提了这么多要求;那么,hashCode() 可怜巴巴的提了点什么要求呢 )
4、obj1.hashCode() == obj1.hashCode() 是 true,则:obj1.equals(obj2) 必须是 true 嘛?
不必须是true,但最好是true。obj1.equals(obj2) 为 false 也行,这时(equals() false,hashCode() true),根据3(equals() false,则 hashCode() 最好 false),这不是好的情况
5、obj1.hashCode() == obj1.hashCode() 是 false,则:obj1.equals(obj2) 必须是 false 嘛?
是的。如若 obj1.equals(obj2) 为true,根据2(equals() true,hashCode() 必须true),那不又返过来使得 hashCode()又true了嘛
HashMap中,如何决定 某个 key 已经存在?
必须满足两条,而且是按这个顺序来的
1、key.hashCode() == keyX.hashCode()
2、key.equals(keyX)
containsKey(Object key) 是如下实现的
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
/**
* Returns the entry associated with the specified key in the
* HashMap. Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
// 注意:
// 1、hash必须是相同的
// hash 通过 hash(key.hashCode())而得到。可以认为 只有参数相同 方法hash()才会返回相同值。即 hashCode() 是相同的
// 2、key.equals(k)
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//注意:
// 1. hash必须相同
// 2、key.equals(k)
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}