public class A {
    private int i=0;
    public int getI() {
return i;
    }
    public void setI(int i) {
this.i = i;
    }
    public int hashCode() {
return i;
    }
    public boolean equals(Object o){
        return (o instanceof A) && (i==((A)o).getI());
    }    public static void main(String[] args){
HashMap<A, String> hm = new HashMap<A,String>();
A a = new A();
         hm.put(a, "a");
         System.out.println("@@@"+hm.get(a));
a.setI(9);
         System.out.println("&&&"+hm.get(a));
    }
}输出结果为什么是:
@@@a
&&&null

解决方案 »

  1.   

    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map.Entry;
    public class A {
        private int i=0;
        public int getI() {
    return i;
        }
        public void setI(int i) {
    this.i = i;
        }
        public int hashCode() {
    return i;
        }
        public boolean equals(Object o){
            return (o instanceof A) && (i==((A)o).getI());
        }    public static void main(String[] args){
         HashMap<A, String> hm = new HashMap<A,String>();
         A a = new A();
            hm.put(a, "a");
             System.out.println("@@@"+hm.get(a));
         a.setI(9);
             System.out.println("&&&"+hm.get(a));
             
             
      Iterator<Entry<A, String>> it = hm.entrySet().iterator();
    while(it.hasNext()){
    Entry<A, String> entry=it.next();
    System.out.println("***"+entry.getKey().hashCode());
    }
    System.out.println("!!!"+a.hashCode());
        }
    }输出结果为:@@@a
    &&&null
    ***9
    !!!9
    hashCode值都是9,请问为什么会输出&&&null?
      

  2.   

    你搞错了,第一个hashCode是0,第二个才是9。不一样。
      

  3.   

    key对象修改了,hashCode已经变了,HashMap中已经找不到这个key了,属于程序错误。
      

  4.   

    这是hashmap的get方法代码,相信你看了以后就明白原因了:
    public Object get(Object key) {
            Object k = maskNull(key);
            int hash = hash(k);
            int i = indexFor(hash, table.length);
            Entry e = table[i]; 
            while (true) {
                if (e == null)
                    return e;
                if (e.hash == hash && eq(k, e.key)) 
                    return e.value;
                e = e.next;
            }
        }