简体   繁体   中英

Why the containValue method returning true even if i override the hashCode() method?

HI even here if I comment out overridden hashcode method in the below code, the output is true for containValue method even the hashcodes are different please help with this. I had overridden equals method, but facing problem with containValue function.

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)));
    } 
}

Hash maps only use hash codes to find keys efficiently. When you ask the map to find a value , it basically has to iterate over all its entries, at which point there's no point in using hashCode() , so it just calls equals .

If you try the map the other way round, with Test as the key instead of the value, that won't work without overriding hashCode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM