嗨,即使在这里,如果我在下面的代码中注释掉覆盖的哈希码方法,即使哈希码不同,containValue 方法的输出也是正确的,请帮忙解决这个问题。我已经重写了 equals 方法,但面临着 containsValue 函数的问题。
import java.util.*;
class Test{
int i;
Test(int i)
{
this.i=i;
}
public boolean equals(Object t)//overriding equals class
{
if(this.i==((Test)t).i){
return true;
}
else{
return false;
}
}
/*public int hashCode() { //overriding the hashcode method
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(1)));
}
}
最佳答案
HashMap 仅使用哈希代码来有效地查找键。当您要求映射查找一个值时,它基本上必须迭代其所有条目,此时使用 hashCode()
没有意义,因此它只是调用等于
。
如果您以相反的方式尝试映射,使用 Test
作为键而不是值,则在不覆盖 hashCode 的情况下不会工作
.
关于java - 为什么即使我重写 hashCode() 方法,containValue 方法也会返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36063803/