在Java中将Integer用作HashMap的键

在Java中将Integer用作HashMap的键

本文介绍了在Java中将Integer用作HashMap的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Recently I was looking for good implementation of hashCode() method in Java API and looked through Integer source code. Didn't expect that, but the hashCode() just returns the backed 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;
    }

这真的很奇怪,因为这里有很多文件,页面和包装致力于这个问题-如何设计好的哈希函数来分配值。

It's really strange as there are a lot of papers and pages as well as packages dedicated to this question - how to design good hash function to distribute values.

最后我得出了以下结论:

Finally I ended up with this conclusion:

Integer 是最不适合使用该键的数据类型,因为所有连续的键都是放在一个垃圾箱中。就像上面的示例中一样。

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

Map<Integer, String> map = HashMap<>();

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

有两个问题,我在谷歌搜索时没有找到答案:

There are two questions, for which I didn't find answers while googled:


  1. 我对关于 Integer 数据类型的结论是否正确?

  2. 如果是真的,为什么在使用幂运算,质数和二进制移位时, Integer的hashCode()方法没有以某些棘手的方式实现?

  1. Am I right with my conclusion regarding Integer data type?
  2. In case it's true, why Integer's hashCode() method don't implemented in some tricky way when power operation, prime numbers, binary shifting are used?


推荐答案

不,该语句是错误的。

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

In fact, the implementation of Integer's hashCode() is the best possible implementation. It maps each Integer value to a unique hashCode value, which reduces the chance of different keys being mapped into the same bucket.

有时候,简单的实现是最好的。

Sometimes a simple implementation is the best.

来自 hashCode的Javadoc () Object 类中:

Integer 是实际上保证不相等对象会出现的少数类之一具有不同的 hashCode()

Integer is one of the few classes that actually guarantees that unequal objects will have different hashCode().

这篇关于在Java中将Integer用作HashMap的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:53