您的位置:首页 > 其它

hashcode、equals和==简单总结

2011-10-25 20:16 288 查看
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

本文出自 “木又寸的技术博客” 博客,请务必保留此出处http://jianshusoft.blog.51cto.com/2380869/697702
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: