【发布时间】:2016-03-16 19:12:33
【问题描述】:
在这里,我试图同时覆盖 equals 方法和哈希码方法。但是 containsValue() 方法抛出 False。甚至哈希码覆盖的类也被调用,但我认为 equals 方法没有被正确调用。请帮我解决这个问题。
import java.util.*;
class Test{
int i;
Test(int i)
{
this.i=i;
}
public boolean equals(Test t)
{
if(this.i==t.i){
return true;
}
else{
return false;
}
}
public int hashCode() { //Overriding hashCode class
int result = 17;
result = 37*result + Integer.toString(i).hashCode();
result = 37*result;
return result;
}
}
class TestCollection13{
public static void main(String args[]){
HashMap<Integer,Test> hm=new HashMap<Integer,Test>();
hm.put(1,new Test(1));
hm.put(2,new Test(2));
hm.put(3,new Test(1));
hm.put(4,new Test(4));
for(Map.Entry m:hm.entrySet()){
Test t2=(Test)m.getValue();
System.out.println(m.getKey()+" "+t2.hashCode());
}
System.out.println(hm.containsValue(new Test(2)));
}
}
【问题讨论】:
-
谢谢你,但我面临的问题是即使没有覆盖 hashCode 方法,它也会返回 true。