Java中的散列键 [英] Hashing Keys in Java

查看:140
本文介绍了Java中的散列键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,当我使用String作为HashMap的关键字时,与使用字符串hashcode作为HashMap中的键的结果相比,结果稍有不同。



任何见解?

解决方案


当我使用字符串hashcode作为HashMap中的键时。 / p>

您不能将哈希码本身用作关键字。哈希代码并不是唯一的 - 完全允许两个不相等的值具有相同的哈希代码。您应该使用字符串本身作为关键字。然后,地图会首先比较哈希代码(以快速缩小候选匹配),然后与 equals 比较真正的字符串相等性。



当然,这是假设你的代码真的是你的问题,例如

  HashMap< String,String> goodMap = new HashMap< String,String>(); 
goodMap.put(foo,bar);

HashMap< Integer,String> badMap = new HashMap< Integer,String>();
badMap.put(foo.hashCode(),bar);

如果这真的是你的代码的样子,只需使用 HashMap< String,字符串> 代替。



来自 Object.hashCode() (强调我的):


hashCode的一般合约是:


  • 只要在执行Java应用程序时多次在同一对象上调用同一对象,hashCode方法就必须始终返回相同的整数,前提是未修改对象的等于比较中使用的信息。如果两个对象根据equals(Object)方法相等,则调用hashCode方法(如果两个对象相等),则此整数不必保持一致,即从应用程序的一次执行到同一应用程序的另一次执行。 在这两个对象中的每一个上都必须产生相同的整数结果。

  • 根据equals(java.lang.Object)方法,如果两个对象不相等,那么对这两个对象的每一个调用hashCode方法必须产生不同的整数结果。然而,程序员应该意识到,为不相等的对象生成不同的整数结果可以提高散列表的性能。



In java, when I use a String as a key for Hashmap I get a little different result than when I use the string hashcode as a key in the HashMap.

Any insight?

解决方案

when I use the string hashcode as a key in the HashMap.

You mustn't use the hash code itself as the key. Hash codes aren't intended to be unique - it's entirely permitted for two non-equal values to have the same hash code. You should use the string itself as a key. The map will then compare hash codes first (to narrow down the candidate matches quickly) and then compare with equals for genuine string equality.

Of course, that's assuming your code really is as your question makes it, e.g.

HashMap<String, String> goodMap = new HashMap<String, String>();
goodMap.put("foo", "bar");

HashMap<Integer, String> badMap = new HashMap<Integer, String>();
badMap.put("foo".hashCode(), "bar");

If that's really what your code looks like, just use HashMap<String, String> instead.

From the docs for Object.hashCode() (emphasis mine):

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

这篇关于Java中的散列键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆