2016-03-17 68 views
0

嗨即使在這裏,如果我在下面的代碼中註釋掉重寫的hashcode方法,輸出對於containsValue方法也是如此,即使hashcode不同,請幫助。我重寫了equals方法,但是卻面臨着與containsValue函數有關的問題。爲什麼即使我重寫hashCode()方法,containsValue方法返回true?

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

請花時間縮進您的代碼 - 目前這非常令人困惑。請注意,當您將所有內容縮進四個空格時(您應該對代碼塊進行縮進),您不需要/不需要反引號。 –

+0

因爲你的'HashMap'中有一個'Test'的實例,所以''Integer''不是'Test' – Ramanlfc

+0

,'i'的值爲'1'。雖然這個值存在於你的'HashMap'中。 – SomeJavaGuy

回答

4

哈希僅映射使用散列碼找到有效。當你要求地圖找到的值時,它基本上必須迭代所有條目,此時使用hashCode()沒有意義,所以它只是調用equals

如果試圖在地圖倒過來,用Test爲重點,而不是價值,即將在不重寫hashCode工作。

相關問題