java - 在 Java 中调用 Map containsKey(E e) 时会发生什么

标签 java dictionary containskey

<小时/>

我检查了源代码:

    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()”方法被调用,所以如果我想在 map 中放置一个自定义对象,我只能重写“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()。 其他 map 类型可能确实不依赖于此方法被重写。

关于java - 在 Java 中调用 Map containsKey(E e) 时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22112400/

相关文章:

java - QueryDSL 从子查询中选择带有别名的值

java - 如何在事件上调用 jquery 函数?

dictionary - 解析 tcl 中的文本文件并创建键值对字典,其中值采用列表格式

仅存储更改的 Python 字典

java - 具有字节数组键和字符串值的 HashMap - containsKey() 函数不起作用

java - 如何使用java在Windows Phone应用程序中发送推送通知?

java - Servlet ServletFileUpload 的最大文件大小

dictionary - F# 将 Map 转换为 Dict 的有效方法(反之亦然)

r - 检查一对列是否在数据框的一行中

java - Java HashMap containsKey