2016-12-13 47 views
2
// this is the hashCode method of Set 
public int hashCode() { 
    int h = 0; 
    Iterator<E> i = iterator(); 
    while (i.hasNext()) { 
     E obj = i.next(); 
     if (obj != null) 
      h += obj.hashCode(); 
    } 
    return h; 
} 



//this is the hashCode method of List 
public int hashCode() { 
    int hashCode = 1; 
    for (E e : this) 
     hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); 
    return hashCode; 
} 

爲什麼java使用這兩種不同的方法?有什麼與Set和List的特性有關嗎? 爲什麼它使用31而不是其他數字? 謝謝!爲什麼Java實現Set和ArrayList的不同hashcode方法?

+1

我回答了關於List vs Set的部分,因爲我在SO上找不到任何其他問題。但約31的位已經回答了:如果您搜索爲什麼散列函數使用素數,請參閱http://stackoverflow.com/questions/299304以及其他答案。 – yshavit

回答

4

集合是無序的,因此{a, b, c}必須具有與{c, b, a}相同的哈希碼。加法是可交換的,因此添加元素的hashCodes會爲您提供該屬性。

列表是有序的,所以當[a, b, c]可能具有相同的哈希碼[c, b, a],它並不需要 - 它會更好,如果沒有,因爲儘可能不相等的對象應該嘗試使用不相等的hashCodes。 ArrayList.hashCode實現具有該屬性。

注意設置和目錄都定義了實現必須如何定義equalshashCodeSet.hashCodeList.hashCode),所以任何(標準)執行這些相應的集合會看起來幾乎相同。這給你一個有用的屬性,即包含相同元素的Set與任何其他Set相同(因此具有相同的hashCode),而不管基礎實現如何。

+0

你的回答非常清楚。謝謝! –

相關問題