hashSet 注意点 重写equals时必须同时重写hashcode
2013-04-24 13:37
513 查看
今天在复习hashSet这块时,重写了equals方法但是没有从写hashcode方法,但是在把对象加到set中是却显示加载的对象不重复,查了下资料得出,在hashSet中判断是不是同一个对象时进行如下操作,源码如下:
以上hashset中的源码,他调用了map的put方法,我们在到map.put去看看:
关键代码在第8行,可以看到在hashmap中先比较key的哈希码在比较key的equals方法,所以在hashset和hashmap中重写equals方法时必须要重写hashcode方法!不然虽然equals方法比较值为true也不能将对象加到集合中
public boolean add(E e) { return map.put(e, PRESENT)==null; }
以上hashset中的源码,他调用了map的put方法,我们在到map.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; 8 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; }
关键代码在第8行,可以看到在hashmap中先比较key的哈希码在比较key的equals方法,所以在hashset和hashmap中重写equals方法时必须要重写hashcode方法!不然虽然equals方法比较值为true也不能将对象加到集合中
相关文章推荐
- 为什么使用HashSet储存对象时必须重写equals和hashcode方法
- 为什么在重写 equals方法的同时必须重写 hashcode方法
- 判断两个对象是否相等,为什么必须同时重写equals()和hashcode()方法
- 判断两个对象是否相等,为什么必须同时重写equals()和hashcode()方法
- 为什么在重写 equals方法的同时必须重写 hashcode方法
- HashSet中的元素必须重写equals方法和hashCode方法
- 重写equals时还必须重写hashCode方法
- why在重写equals时还必须重写hashcode方法
- 重写equals方法时必须重写hashCode方法的理由
- 重写equal 的同时为什么必须重写hashcode?
- 为什么重写hashCode 同时equals
- HashSet与重写equals(),hashcode():判断“数组“对象相等
- HashSet以及重写equals()和hashCode()
- 使用HashMap,如果key是自定义的类,就必须重写hashcode()和equals()。
- 重写equals()方法同时还需要重写hashCode()方法
- JAVA中重写equals()方法的同时要重写hashcode()方法
- 补充HashSet集合hashCode和equals的重写,保证元素的不重复
- 重写equals时还必须重写hashcode方法,详解
- 详解重写equals()方法就必须重写hashCode()方法的原因
- HashSet (需要重写hashCode和equals方法)