java - 为什么即使我重写 hashCode() 方法,containValue 方法也会返回 true?

标签 java hashcode

嗨,即使在这里,如果我在下面的代码中注释掉覆盖的哈希码方法,即使哈希码不同,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/

相关文章:

java - 无法对非静态方法进行静态引用问题

java - 为什么写入字节数组时,ObjectOutputStream.writeObject 比写入字节更快?

java - 具有空对象模式的 DAO

java - 为什么我们需要检查两次哈希码?

android - 字符串 hashCode() : always the same result?

java - 如何从链接到 .jar 文件的 java 数组中删除值?

java - 返回流而不是列表

java - 我应该重写 Collections 的 hashCode() 吗?

python - 为什么 Sets 允许多个具有不同 hashCode 的相同对象?

java - 覆盖哈希码方法时获取 "Stack overflow error "