gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:05:14 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com