繁体   English   中英

在Java中调用地图的containsKey(E e)时会发生什么

[英]what happend when the Map's containsKey(E e) is called in Java


我已经检查了源代码:

    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()”方法吗?

这是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() 其他地图类型的确可能不依赖于此方法被覆盖。

  1. 从Object.equals API中:通常,无论何时重写此方法,都必须重写hashCode方法,以便维护hashCode方法的常规协定,该协定规定相等的对象必须具有相等的哈希码。 您可以在“有效Java”项目9中找到更详细的说明:覆盖均等时,始终覆盖hashCode。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM