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

标签 java integer hashcode java-6

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

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/

相关文章:

java - 使用 Swing 绘制选择框

java - 如何在 Java 中获取 Double 的最大最安全整数

c++ - 如何从它的数字中得到一个整数?

arrays - Scala:将数组放入 Set 或 Map 的轻量级方法

java - 运行 Java 应用程序 NoClassDefFoundError

java - 我怎样才能在Java中获得n位数字的最大十进制值?

C++ 为变量分配异常大的内存

Python错误: Int object not subscriptable

java - equals 和 hashCode 未按预期工作

java - 奇怪的 Java 哈希码(使用 Lombok)非确定性行为