java - Java 中 HashMap 的用处

标签 java data-structures

因此,我正在应对一项编程挑战,我想存储超过 128 个 <int, int>. 类型的键值对。

由于 HashMap 不能接受原语,所以我使用 <Integer, Integer >。我遇到了一个问题:

HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
Integer x = new Integer(130);
map.put(x, x);

稍后在我的代码中,我计算需要从 map 中检索的值作为整数。我尝试使用以下方法检索它:

int calculated = 130;
Integer y = new Integer(calculated);
map.get(y)

这将导致 NullPointerException,因为 x 和 y 的 HashCode 不同(这是预期的,因为 Integer 类仅保留 -128 到 127 之间的值的缓存)。

我的问题是,如果我想在 Java 中使用类似映射的结构来存储大量键值对,我该怎么做?

[编辑]:谢谢大家的回复!在重构了我的一些逻辑之后,问题不再存在(这不是整数本身的问题)。感谢您让我再次欣赏在 Java 中使用 HashMap :)

最佳答案

This will cause a NullPointerException because the HashCode of the x and y are different (which is expected because the Integer class keeps a cache of values only between -128 and 127).

这无关紧要。 Integer 适本地覆盖 hashCode()equals(),这就是在 中查找不相同的对象所需的全部内容> HashMap 。 (两个相等的 Integer 值的哈希码将相同,即使它们不是相同的 Integer 对象。)

应该没问题:

Map<Integer, Integer> map = new HashMap<>();
Integer x = 130;
Integer y = 130;
System.out.println(x == y); // False (on my machine)
map.put(x, 1000);
System.out.println(map.get(y)); // 1000

此外,仅语句 map.get(y) 不会抛出 NullPointerException,除非 mapy > is null...即使找不到匹配项,也会返回null,而不抛出异常。

请注意,您不需要调用 new Integer(...) - 如果您这样做,装箱值的缓存无论如何都是无关紧要的。例如:

Integer a = new Integer(5);
Integer b = new Integer(5);
System.out.println(a == b); // False, always

Integer c = 5;
Integer d = 5;
System.out.println(c == d); // True, always, due to caching of small boxed values

关于java - Java 中 HashMap 的用处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26113576/

相关文章:

c - 在循环链表开头插入

c++ - 为什么要用树状数据结构来表示文字冒险游戏中的数据?

java - 如何将 JMS 队列视为临时存储?

java - 在 JDBC 中使用时,查询返回的行数少于 SQL 开发人员

java - Atomikos、Tomcat、事务日志和不观察系统属性

mysql - 什么数据存储模型用于存储维基百科中的文章

c - C语言中使用stat()获取文件的长度

json - 设计数据结构

java - 如何获取SQLite 'VACUUM'进度

java - 跨平台 git : possible strategies to handle platform specific files