微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

地图条目的哈希码值

如何解决地图条目的哈希码值

根据 javadocs 哈希码,map.entry 定义为:

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.Entry 中提取的实际代码,如 HashMap 实现中所定义。 ^ 运算符是 Java 的异或运算符。

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

但是,只要满足hashCode的合同,计算方法或具体结果应该对用户没有影响。

,

是的,^ 的意思是“异或”。 Here is a list of all operators

这似乎是网络搜索找到的东西,比提出 SO 问题要快得多。

,

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

不正确的解释 - 保留上下文,因此下面的评论有意义

这确保具有相同 hashCode() 值的 Map.Entry 对象的两个实例保证具有相同的 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");
 }
}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。