java - 在 Java 中使用 Integer 作为 HashMap 的键

标签 java collections

最近我在寻找 hashCode() 的良好实现Java API 中的方法并查看 Integer源代码。没想到,但是hashCode()只返回支持的 int值(value)。

public final class Integer ... {
private final int value;
...
    public int hashCode() {
        return Integer.hashCode(value);
    }
    public static int hashCode(int value) {
        return value;
    }

这真的很奇怪,因为有很多论文和页面以及专门解决这个问题的包 - 如何设计好的散列函数来分配值。

最后我得出了这个结论:
Integer当与 HashMap 一起使用时,是键的最差数据类型候选者,因为所有连续的键都将放在一个 bin/bucked 中。就像上面的示例一样。
Map<Integer, String> map = HashMap<>();

for (int i = 1; i < 10; i++) {
    map.put(Integer.valueOf(i), "string" + i);
}

有两个问题,我在谷歌搜索时没有找到答案:
  • 我对 Integer 的结论是否正确?数据类型?
  • 如果是真的,为什么Integer's hashCode()当使用幂运算、质数、二进制移位时,方法没有以某种棘手的方式实现?
  • 最佳答案

    Integer is the worst data type candidate for a key when used with HashMap, as all consecutive keys will be places in one bin



    不,这种说法是错误的。

    其实执行IntegerhashCode()是最好的实现。它映射每个 Integer值到唯一 hashCode值,这减少了不同键被映射到同一个存储桶的机会。

    有时一个简单的实现是最好的。

    来自 hashCode() 的 Javadoc在 Object类(class):

    It is not required that if two objects are unequal according to the java.lang.Object.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.


    Integer是少数几个真正保证不相等的对象会有不同的类之一 hashCode() .

    关于java - 在 Java 中使用 Integer 作为 HashMap 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50273035/

    相关文章:

    java - 为什么Java没有类似Comparator的接口(interface),而是用于散列的?

    java - 使用mapTree集合并需要更多颜色

    java - Spring boot META-INF/build-info.properties 不在工件中

    java - Java格式错误的url异常,用于简单的url

    java - 提取整数的最右边的 N 位

    java - 在 Java 中解析 OCL?

    python - 在 python 中,如何将两个具有关联计数列表的非常大的列表合并为一个具有关联计数列表的列表?

    ruby-on-rails - 如何在 ActiveRecord 类方法中使用 'map' 方法?

    Java IO : Why does the numerical representation of line feed appear on the console when reading from stdin?

    Magento 1.7 向集合过滤器添加多个属性