Java HashMap不返回基于键的值
我试图使用一个HashMap,将我的类单元格作为键。但是,将项目放入HashMap后,对该项目调用contains将返回falseJava HashMap不返回基于键的值,java,hashmap,Java,Hashmap,我试图使用一个HashMap,将我的类单元格作为键。但是,将项目放入HashMap后,对该项目调用contains将返回false public static void main(String args[]) { HashMap<Cell, String> map = new HashMap<Cell, String>(); map.put(new Cell(0,0), "Bob"); System.out.println(
public static void main(String args[]) {
HashMap<Cell, String> map = new HashMap<Cell, String>();
map.put(new Cell(0,0), "Bob");
System.out.println(map.containsKey(new Cell(0,0)));
System.out.println(new Cell(0,0).equals(new Cell(0,0)));
}
publicstaticvoidmain(字符串参数[]){
HashMap=newHashMap();
map.put(新单元(0,0),“Bob”);
System.out.println(map.containsKey(新单元(0,0));
System.out.println(新单元(0,0).equals(新单元(0,0));
}
这将打印出false和true,其中应该打印true和true,因为根据映射,docs containsKey使用.equals()。我做错了什么?考虑一下如何实现
HashMap
。放置时,它首先计算对象hashCode()
,以确定将对象放置在哪个bucket中。当它试图检索一个对象时,它再次获取它的hashCode()
,标识目标bucket,遍历bucket中的链表,对每个对象调用equals()
。如果找到匹配项,则返回
换句话说,当您使用HashMap
时,您需要有一个正确且匹配的equals()
和hashCode()
实现
从
对象继承的默认hashCode()
方法不会正确返回相同的hashCode()
,除非对象引用相同。在您的情况下,它们不是。多次调用新单元格(0,0)会产生具有不同哈希代码的不同对象。您应该为Cell类实现hashCode。您可能忘记为Cell
实现hashCode()
函数,这也是在HashMap
中使用用户定义类所必需的。下面是实现hashcode()
函数的一种简单且通常准确的方法:
int hashcode(){
return (field1.toString()+field2.toString()+...+fieldN.toString()).hashcode();
}
其中field1
到fieldN
是您的类中的字段。如果字段是primative(即int
),只需取出toString()
,这很可能是因为没有实现equals()
和hashCode()
。在Java中,经验法则是,如果实现一个,那么必须实现另一个。在您的情况下,它是必需的,因为HashMap
使用它们
您创建了两个具有两个单独地址的单独对象。如果没有这些方法,JVM就无法知道对象是“相同的”
请参见,您还需要正确地实现hashCode()
。或者根本不实现equals,hashCode。如果重写equals,那么也应该实现hashCode如果不重写hashCode()
,那么它将只使用默认的对象方法,这就是为什么尽管具有相同的值,但每个对象的值都不同的原因。请尝试System.out.println(新单元格(0,0).hashCode()==新单元格(0,0).hashCode()代码>毕竟它是一个HashMap。