日期:2014-05-20  浏览次数:20690 次

java源代码研究:HashMap的containsKey
下面是代码,谁能跟我说说为什么要加e.hash == hash 这句话
Java code
/**
     * Returns the entry associated with the specified key in the
     * HashMap.  Returns null if the HashMap contains no mapping
     * for the key.
     */
    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key.hashCode());
        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;
    }


------解决方案--------------------
两个条件都有同时满足吧.有可能一个满足了两一个却是不满足的
------解决方案--------------------
判断两个对象是否相同,如果2个对象相同,那么返回的hashcode必须相同
所以平时如果要重写equals方法,那么hashcode方法也必须重写
这里,如果key的hashcode不同,那么可以肯定不是同一个key
------解决方案--------------------
判断两个对象是否相同,如果2个对象相同,那么返回的hashcode必须相同 
所以平时如果要重写equals方法,那么hashcode方法也必须重写 

------解决方案--------------------
为了保证是同一个对象,是要用equals检查,equals效率低的。比较哈希值速度更快,应该是直接定位对象存储的物理地址
如果两个对象相同,那么它们的hashCode值一定要相同所以先e.hash == hash,如果两个对象的hashCode相同,它们并不一定相同所以后面再key.equals(k)
------解决方案--------------------
探讨
引用:
为了保证是同一个对象,是要用equals检查,equals效率低的。比较哈希值速度更快,应该是直接定位对象存储的物理地址
如果两个对象相同,那么它们的hashCode值一定要相同所以先e.hash == hash,如果两个对象的hashCode相同,它们并不一定相同所以后面再key.equals(k)

兄弟你回答反了呵呵

------解决方案--------------------
真不厚道。知道答案就写出来嘛。时间很宝贵
------解决方案--------------------
给楼主举个例子

Java code

package test;

import java.util.HashMap;
import java.util.Map;

public class Test {
    
    public static void main(String[] args) {
        Map<Test1, String> m = new HashMap<Test1, String>();
        Test1 t1 = new Test1("test");
        Test1 t2 = new Test1("test");
        System.out.println(t1.equals(t2));//这里将始终输出false,因为重写了equals.
        m.put(t1, "aaaa");
//        这里,如果把hashCode注释掉,那么这里输出的将是false,原因是t1和t2的hashCode不一样
//        反过来说你如果把e.hash == hash注释掉,即使你认为t1和t2是同一个key,但是返回的hashCode不一样,所以t1和t2还不是同一个对象
        System.out.println(m.containsKey(t2));
    }
}

class Test1{
    private String test;

    public Test1(String t){
        test = t;
    }
    
    public String getTest() {
        return test;
    }
    
    public boolean equals(Object o){
        Test1 t = (Test1) o;
        return test.equals(t.getTest());
    }
    
    public int hashCode(){
        return test.hashCode();
    }
    
}

------解决方案--------------------
帮顶~!
------解决方案--------------------
4楼有提到,根据key提取entry 我想也许是出于效率考虑,如果key的hash不同,就已经没有再判断计算下去的必要了
如果相同,才作进一步判断,因为不等或不同的key也是有可能具有相同hash的,这一点有sun文档佐证


* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the <tt>hashCode</tt> method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hashtables.