java - HashMap 以非连续顺序返回值

标签 java map hashmap

我在 HashMap 中插入四个具有不同键的值。 代码片段:

HashMap<Integer, String> choice = new HashMap<Integer, String>();

choice.put(1, "1917");
choice.put(2, "1791");
choice.put(3, "1902");
choice.put(4, "1997");

但是当我打印 map 值时,它返回的结果类似于:

{4=1997, 1=1917, 2=1791, 3=1902}

如何按照我放置/插入的方式按顺序获取 map 值?

最佳答案

您可以使用 LinkedHashMap instead ,这将保持插入顺序:

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

您可以像这样修改您的代码:

Map<Integer, String> choice = new LinkedHashMap<Integer, String>();

//rest of the code is the same

关于java - HashMap 以非连续顺序返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11612860/

相关文章:

java - 如何从一张 map 中删除另一张 map 的元素?

hashmap - 如何为包含具有可变引用的 HashMap 的结构实现 find_or_create 方法

java - 运行代码格式化程序时,我可以阻止 Intellij 拆分字符串文字吗?

java - 使用 Java 将数据插入 mySQL DB 时出错

java - 使用键复合键进行高效的 HashMap 检索(由 2 个枚举构建)

grails - 域使用addTo Map导致错误

R:Yahoo/Bing 或其他替代 Google 地球的地理编码方法?

java - 套接字的损坏的 ObjectOutputStream

java - 使用 perf 进行分析时,JMH 给出 <not counted> 值

c++ - 在 std::map 和 std::unordered_map 之间进行选择