gpt4 book ai didi

java - java(windows平台)中两个Integer解析为相同的hashcode

转载 作者:行者123 更新时间:2023-12-02 06:14:04 26 4
gpt4 key购买 nike

我遇到了两个整数在测试用例中解析为相同哈希码的问题,如下所示:

public class Test {

private final static Logger log = LoggerFactory.getLogger(Test.class);

private final static LinkedHashMap<Integer,Integer> map = new LinkedHashMap<Integer,Integer>();
/**
* @param args
*/
public static void main(String[] args) {
int j=0;
for(int i=0;i<10000;i++){
++j;
int hash = System.identityHashCode(i);
if(map.containsKey(hash)){
log.info("hashcode of key "+i+" was conflict with "+map.get(hash)+" hashcode was:"+hash);
}else{
map.put(hash, i);
}
}
log.info("length of map:"+map.size()+" expected:"+j);
}
}

输出如下:

2014-02-08 12:10:59,723 [main] INFO: hashcode of key 1947 was conflict with 422 hashcode was:9578500  <reactive.lib.Test>
2014-02-08 12:10:59,725 [main] INFO: hashcode of key 2246 was conflict with 1966 hashcode was:14850080 <reactive.lib.Test>
2014-02-08 12:10:59,736 [main] INFO: length of map:9998 expected:10000 <reactive.lib.Test>

我期望所有 Integer 都有一个唯一的哈希码 - 谁能解释一下?如果有帮助的话,这个测试是在 Windows 上的 JDK1.6 下进行的。

最佳答案

您正在使用System.identityHashCode:

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().

对于Integer,它会重写hashCode(),以便每个值的哈希码等于其int 值。通过使用此函数而不是 hashCode(),您可能会遇到更多冲突。

一般来说,哈希码允许不唯一 - hashCode() 可能会为所有对象返回 1,但它仍然有效。仅要求为相等的对象返回相同的数字,并且建议它们尽可能不唯一,以便更有效地使用哈希表。

来自javadoc :

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 - java(windows平台)中两个Integer解析为相同的hashcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com