简体   繁体   English

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

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


i've checked the source code : 我已经检查了源代码:

    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);
    }

from the source code , it shows only the "equal()" method has been called , so if i wanna put an custom Object in a map , i could only have to override the "equal()" method. 从源代码中,它显示仅调用了“ equal()”方法,因此,如果我想在地图中放置自定义对象,则只需覆盖“ equal()”方法。 so i did an experiment , the result is negative ... i have to override both "equals()" and "hashCode()" . 所以我做了一个实验,结果是负的。我必须重写“ equals()”和“ hashCode()”。 so my question is : 所以我的问题是:

  1. why both method (equals() ,hashCode()) has to be override. 为什么必须重写两个方法(equals(),hashCode())。
  2. does the "==" operation internally calls the "hashCode()" method? “ ==“操作在内部调用“ hashCode()”方法吗?

This is AbstractMap 's implementation. 这是AbstractMap的实现。 HashMap , which overrides it, implements it as follows: 覆盖它的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);
}

As you can see, this depends on the hashCode() . 如您所见,这取决于hashCode() Other map types may indeed not depend on this method being overriden. 其他地图类型的确可能不依赖于此方法被覆盖。

  1. From Object.equals API: it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. 从Object.equals API中:通常,无论何时重写此方法,都必须重写hashCode方法,以便维护hashCode方法的常规协定,该协定规定相等的对象必须具有相等的哈希码。 You can find more detailed explanation in "Effective Java" Item 9: Always override hashCode when you override equals. 您可以在“有效Java”项目9中找到更详细的说明:覆盖均等时,始终覆盖hashCode。

  2. No it does not, it is simply pointers comparison, just like comparing two ints 不,不是,它只是指针比较,就像比较两个整数

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

相关问题 当我在Java中说“catch(Exception e){}”时,它叫什么? - What is it called when I say “catch (Exception e) {}” in Java? 在Java中捕获e(rror)时该怎么办 - What to do when catching e(rror) in Java JAVA中(ë|e)是什么意思 - What is the mean of (ë|e) in JAVA 如何使用 Java 的 map containsKey() 方法解决? - How can I solve with Java's map containsKey() method? JAVA:当我调用 object 的 getter 方法时发生了什么,它实际上是从它的超类扩展方法 - JAVA: what happend when i call a getter method of a object which actually extend the method from it's superClass Java递归通用模板:这是什么意思……S扩展了Writer <E> &gt;扩展实体 <E,S> - Java Recursive generic template: what does this mean by … S extends Writer<E>> extends Entity<E,S> Java Hash Map containsKey 在不应该返回 true 时返回 true - Java Hash Map containsKey is returning true when it should not 通过java 8接口改进map中的containsKey - Improve if containsKey in map by java 8 interface Java列表<E>到地图<P, List<E> &gt; 键是 E 的某个属性,值是具有该属性的 E - Java List<E> to Map<P, List<E>> were key is some property of E and value is E with that property add(E e,Object [] elementData,int s)方法有什么作用? - What's add(E e, Object[] elementData, int s) method for?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM