1, ==是比较句柄,若ob1==ob2,也就是两个句柄指向一个对象。所以ob1.hashcode()==ob2.hashcode()和ob1.equals(ob2) == true;
2,hashcode相同的两个对象,ob1.equals(ob2)不一定为true;ob1.equals(ob2)为true的两个对象,hashcode应该相同。即覆写equals方法时应同时覆写hashcode方法
3,hashcode一般用到HashSet,HashMap中,根据hashcode来确定存储位置,如果hashcode相同,再用equals来判断Set中的唯一性。
HashMap中put方法的源代码是:
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;
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;
}
看e.hash == hash && ((k = e.key) == key || key.equals(k))这句,即先判定hashcode是否相同,再判断equals是否为true