在Java HashMap中使用对象作为键
发布时间:2020-12-15 04:28:03  所属栏目:Java  来源:网络整理 
            导读:package test;import java.util.HashMap;public class test { public static void main(String args[]) { HashMapID,String h = new HashMapID,String (); String b; ID id1 = new ID(100); ID id2 = new ID(200); ID id3 = new ID(200); h.put(id1,"apple")
                
                
                
            
                        package test;
import java.util.HashMap;
public class test {
    public static void main(String args[]) {
        HashMap<ID,String> h = new HashMap<ID,String> ();
        String b;
        ID id1 = new ID(100);
        ID id2 = new ID(200);
        ID id3 = new ID(200);
        h.put(id1,"apple");
        h.put(id2,"pear");
        **System.out.println(h.containsKey(id3));**
    }
}
class ID {
    Integer code;
    public ID(Integer id) {
        this.code = id;
    }
    @Override
    public int hashCode()
    {
        return code.hashCode();
    }
    @Override
    public boolean equals(Object o)
    {
        return this.code.equals(o);
    }
} 
 该程序的输出是“假”.我无法理解这个结果.我实现了hashCode和equals,它们被覆盖了.我不知道如何解决.如何在java HashMap中使用对象作为键? 解决方法
 你的equals实现是错误的: 
  
  
  
        public boolean equals(Object o)
{
    return this.code.equals(o); // this will never return true,// since you are comparing an Integer instance
                                // to an ID instance
} 
 您应该将此代码与其他代码进行比较: public boolean equals(Object o)
{
    if (!(o instanceof ID))
        return false;
    ID oid = (ID) o;
    return this.code.equals(oid.code);
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
