日期:2014-05-20 浏览次数:20979 次
/**
     * 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;
    }
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.