[英]Using Objects as keys in Java HashMap
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);
}
}
the output of this program is "false". 该程序的输出是“假”。 I can't understand of this result.
我无法理解这个结果。 I implemented hashCode and equals which are overrided.
我实现了hashCode和equals,它们被覆盖了。 I don't have an idea how to solve.
我不知道如何解决。 How to use objects as keys in java HashMap?
如何在java HashMap中使用对象作为键?
Your equals implementation is wrong : 你的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
}
You should compare this code to the other code: 您应该将此代码与其他代码进行比较:
public boolean equals(Object o)
{
if (!(o instanceof ID))
return false;
ID oid = (ID) o;
return this.code.equals(oid.code);
}
Wrong Implementation of equals
method. 错误的
equals
方法的实现。 According to your implementation it executes the Integer
class equals method. 根据您的实现,它执行
Integer
类equals方法。 We should handle the logic without execute library classes equals
methods. 我们应该在没有执行库类
equals
方法的情况下处理逻辑。
@Override
public boolean equals(Object o) {
if (o == null || ((o instanceof ID) && o.hashCode() != this.hashCode())) {
return false;
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.