0

我检查了源代码:

    public boolean containsKey(Object key) {
        Iterator<Map.Entry<K,V>> i = entrySet().iterator();
        if (key==null) {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    return true;
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey())) 
                    return true;
            }
        }
        return false;
    }


 public boolean equals(Object obj) {
        return (this == obj);
    }

从源代码中,它只显示了“equal()”方法已被调用,所以如果我想在地图中放置一个自定义对象,我只需要覆盖“equal()”方法。所以我做了一个实验,结果是否定的......我必须同时覆盖 "equals()" 和 "hashCode()" 。所以我的问题是:

  1. 为什么必须覆盖这两种方法(equals(),hashCode())。
  2. “==”操作是否在内部调用“hashCode()”方法?
4

2 回答 2

3

这是AbstractMap' 的实现。HashMap,它覆盖它,实现它如下:

public boolean containsKey(Object key) {
    return getEntry(key) != null;
}

final Entry<K,V> getEntry(Object key) {
    if (size == 0) {
        return null;
    }

    int hash = (key == null) ? 0 : hash(key);
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}

final int hash(Object k) {
    int h = hashSeed;
    if (0 != h && k instanceof String) {
        return sun.misc.Hashing.stringHash32((String) k);
    }

    h ^= k.hashCode();

    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}

如您所见,这取决于hashCode(). 其他地图类型可能确实不依赖于被覆盖的此方法。

于 2014-03-01T09:25:46.473 回答
3
  1. 来自 Object.equals API:通常需要在任何时候重写 hashCode 方法,以维护 hashCode 方法的一般约定,即相等的对象必须具有相等的哈希码。你可以在“Effective Java”第 9 条中找到更详细的解释:覆盖 equals 时始终覆盖 hashCode。

  2. 不,它不是,它只是指针比较,就像比较两个整数一样

于 2014-03-01T09:27:10.910 回答