簡體   English   中英

Map 條目的哈希碼值

[英]Hashcode value for Map Entry

根據 map.entry 的 javadocs 哈希碼定義為:

int hashCode()
  Returns the hash code value for this map entry. The hash code of a map entry e is defined to be:
    (e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
    (e.getValue()==null ? 0 : e.getValue().hashCode())

請確認,如果按位 XOR 運算符用於計算 map 條目的哈希碼值?

下面是取自Map.Entry的實際代碼,如HashMap實現中定義的那樣。 ^運算符是 Java 的異或運算符。

public final int hashCode() {
       return Objects.hashCode(key) ^ Objects.hashCode(value);
}

但是,只要滿足hashCode的約定,計算方法或具體結果對用戶應該沒有任何影響。

是的, ^表示“異或”。 這是所有運營商的列表

這肯定看起來像 web 搜索會比詢問 SO 問題快得多。

是的,Map.Entry 的 hashCode() 返回鍵和值的 hashCode 的按位異或。

不正確的解釋 - 留作上下文,所以下面的評論是有意義的

這確保了具有相同 hashCode() 值的 Map.Entry object 的兩個實例具有相同的 Key 和 Value 屬性。 (假設 hashCode() 方法在用作鍵和值的類型中都被正確覆蓋)

是的,它確實是一個按位異或運算符。 我嘗試使用 ^ 運算符對 hashcode() 方法 & 得到相同的結果。

import java.util.*;
class TreeMapExample {
public static void main(String args[]) {
 // Creating TreeMap object
 TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
 // Adding elements to the Map
 tm.put("Chaitanya", 27);
 tm.put("Raghu", 35);
 tm.put("Rajeev", 37);
 tm.put("Syed", 28);
 tm.put("Hugo", 32);

 // Getting a set of the entries
 Set set = tm.entrySet();
 // Get an iterator
 Iterator it = set.iterator();
 // Display elements
 int hash;
 while(it.hasNext()) {
    Map.Entry me = (Map.Entry)it.next();
    System.out.println("Key: "+me.getKey() + " & Value: "+me.getValue());
    System.out.println("hashcode value by method : "+me.hashCode());
    hash = me.getKey().hashCode() ^ me.getValue().hashCode();
    System.out.println("hashcode value by operator : "+me.hashCode()+"\n");
 }
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM