java.util.Set.contains(Object o)的怪异行为



关于java.util.Set.contains(Object o)的文档说:

当且仅当此集合包含元素e,使得(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;
    }
}

那么,为什么下面的代码打印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

一个解决方案是重写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

覆盖equals(Object)时,还需要覆盖hashcode()

具体地,必须实现这些方法,使得如果a.equals(b)true,则a.hashcode() == b.hashcode()都是true。如果不遵守此不变量,则HashMapHashSetHashtable将不能正常工作。

对象API中指定了hashcode()equals(Object)应如何操作的技术细节。


那么,如果你弄错了,为什么基于哈希的数据结构会崩溃呢?基本上是因为哈希表的工作原理是使用哈希函数的值来缩小要与"候选"进行比较的值集。如果候选者的哈希码与表中某个对象的哈希码不同,那么查找算法很可能无法与表中的对象进行比较。。。即使对象是相等的。

HashSet将仅在元素共享相同的hashCode()时使用equals(),因此需要覆盖两者。以下是HashSet#contains()使用的代码的相关部分(请注意,HashSetHashMap支持):

  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       }

不这样做违反了Object#hashCode()的合同,该合同规定:

如果根据equals(Object)方法,两个对象相等,则对这两个对象中的每一个调用hashCode方法必须产生相同的整数结果。

相关内容

最新更新