Map项的hashcode值

ql3eal8s  于 2021-06-26  发布在  Java
关注(0)|答案(4)|浏览(213)

根据javadocs,map.entry的hashcode定义为:

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())

请确认,是否使用位异或运算符来计算Map项的hashcode值?

7kjnsjlb

7kjnsjlb1#

下面是从 Map.Entry 定义见 HashMap 实施。这个 ^ 运算符是java的异或运算符。

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

但是,计算方法或具体结果对用户不产生任何影响,只要合同 hashCode 他很满意。

roejwanj

roejwanj2#

是的,它确实是一个按位异或运算符。我尝试了使用^运算符对这两个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");
 }
}
}
yrdbyhpb

yrdbyhpb3#

对, ^ 表示“xor”。以下是所有运算符的列表。
这似乎是一个网络搜索要比问一个问题快得多的东西。

uelo1irk

uelo1irk4#

是,map.entry的hashcode()返回键和值的hashcode的按位异或。
不正确的解释-保留在适当的地方,以便下面的评论有意义
这样可以确保具有相同hashcode()值的map.entry对象的两个示例具有相同的键和值属性(假设hashcode()方法在用作键和值的类型中都被正确重写)

相关问题