根据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())
Plz确认,是否使用逐位XOR运算符来计算映射条目的哈希码值?
是的,^
的意思是"XOR"。这是所有操作员的列表。
这看起来肯定比问SO问题要快得多。
这是从HashMap
实现中定义的Map.Entry
获取的实际代码。^
运算符是Java的异或运算符。
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
然而,只要满足hashCode
的合同,计算方法或具体结果对用户应该没有任何影响。
是的,hashCode((用于Map。Entry返回键和值的hashCodes的逐位XOR。
解释不正确-保留在上下文中,因此下面的注释有意义
这确保了映射的两个实例。具有相同hashCode((值的条目对象保证具有相同的Key和value属性。(假设hashCode((方法在用作Key和Value的Types中都被正确重写(
是的,它确实是一个逐位XOR运算符。我试过&对于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");
}
}
}