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方法的源代码是:
看e.hash == hash && ((k = e.key) == key || key.equals(k))这句,即先判定hashcode是否相同,再判断equals是否为true
本文出自 “木又寸的技术博客” 博客,请务必保留此出处http://jianshusoft.blog.51cto.com/2380869/697702
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
相关文章推荐
- 3、Object对象的两大方法(hashCode-equals)总结
- java中equals和hashcode方法总结
- java中hashCode方法与equals方法的用法总结
- java中hashCode方法与equals方法的用法总结
- equals与hashCode总结
- java里面的equals和hashcode的总结
- java中hashCode方法与equals方法的用法总结
- java中的equals()和hashcode()方法总结
- Java hashCode() equals()总结
- 总结Java equals()和hashCode()的联系
- java 中hashcode和equals 总结
- Object 开发中常用的重写方法总结toString,equals,hashCode,compareTo
- Java equals()和hashCode()重写总结
- Hashcode、Equals 总结
- java中hashCode方法与equals方法以及contains方法的用法总结
- java中hashCode方法与equals方法的用法总结_java_脚本之家
- String的equals以及hashcode比较总结
- 改写equals与hashCode的简单方法
- hashcode和equals 简单的方法也可能引发问题
- Object 开发中常用的重写方法总结toString,equals,hashCode,compareTo