sp0*_*00m 7 java contains equals set
该DOC约java.util.Set.contains(Object o)说:
当且仅当此set包含元素e时返回true(o == null?e == null:o.equals(e)).
也就是说,这是一个POJO(你可以看到,我覆盖了它的equals方法):
public class MonthAndDay {
private int month;
private int day;
public MonthAndDay(int month, int day) {
this.month = month;
this.day = day;
}
@Override
public boolean equals(Object obj) {
MonthAndDay monthAndDay = (MonthAndDay) obj;
return monthAndDay.month == month && monthAndDay.day == day;
}
}
Run Code Online (Sandbox Code Playgroud)
那么,为什么以下代码打印false而不是true?
Set<MonthAndDay> set = new HashSet<MonthAndDay>();
set.add(new MonthAndDay(5, 1));
System.out.println(set.contains(new MonthAndDay(5, 1)));
// prints false
Run Code Online (Sandbox Code Playgroud)
一个解决方案是重写contains(Object o)方法,但原始方法应该(几乎)完全相同,我错了吗?
Set<MonthAndDay> set = new HashSet<MonthAndDay>() {
private static final long serialVersionUID = 1L;
@Override
public boolean contains(Object obj) {
MonthAndDay monthAndDay = (MonthAndDay) obj;
for (MonthAndDay mad : this) {
if (mad.equals(monthAndDay)) {
return true;
}
}
return false;
}
};
set.add(new MonthAndDay(5, 1));
System.out.println(set.contains(new MonthAndDay(5, 1)));
// prints true
Run Code Online (Sandbox Code Playgroud)
Ste*_*n C 15
覆盖时,equals(Object)您还需要覆盖hashcode().
具体而言,这些方法必须被实现,如果a.equals(b)是true,则a.hashcode() == b.hashcode()是一切true.如果这个不变的不尊重,那么HashMap,HashSet并且Hashtable将无法正常工作.
如何hashcode()和equals(Object)应该表现的技术细节在Object API 中指定.
那么为什么基于哈希的数据结构如果你弄错了呢?好吧,基本上是因为哈希表通过使用哈希函数的值来缩小要与"候选"进行比较的值集合.如果候选的哈希码与表中某个对象的哈希码不同,那么查找算法很可能不会与表中的对象进行比较...即使对象相等.
HashSet只会用equals() ,如果要素共享相同的hashCode(),因此,你需要同时重写.以下是代码的相关部分HashSet#contains()(注意HashSet由a支持HashMap):
355 /**
356 * Returns the entry associated with the specified key in the
357 * HashMap. Returns null if the HashMap contains no mapping
358 * for the key.
359 */
360 final Entry<K,V> getEntry(Object key) {
361 int hash = (key == null) ? 0 : hash(key.hashCode());
362 for (Entry<K,V> e = table[indexFor(hash, table.length)];
363 e != null;
364 e = e.next) {
365 Object k;
366 if (e.hash == hash &&
367 ((k = e.key) == key || (key != null && key.equals(k))))
368 return e;
369 }
370 return null;
371 }
Run Code Online (Sandbox Code Playgroud)
不这样做,违反了合同Object#hashCode(),其中规定:
如果根据
equals(Object)方法两个对象相等,则hashCode在两个对象中的每一个上调用方法必须产生相同的整数结果.
| 归档时间: |
|
| 查看次数: |
9412 次 |
| 最近记录: |