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