本文翻译自:How to preserve insertion order in HashMap? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
I'm using a HashMap
. 我正在使用HashMap
。 When I iterate over the map, the data is returned in (often the same) random order. 当我遍历地图时,数据以(通常是相同的)随机顺序返回。 But the data was inserted in a specific order, and I need to preserve the insertion order. 但是数据是按特定顺序插入的,我需要保留插入顺序。 How can I do this? 我怎样才能做到这一点?
#1楼
参考:https://stackoom.com/question/iwD3/如何在HashMap中保留插入顺序-重复
#2楼
LinkedHashMap
is precisely what you're looking for. LinkedHashMap
正是您所需要的。
It is exactly like HashMap
, except that when you iterate over it, it presents the items in the insertion order. 它与HashMap
完全相同,只是当您迭代它时,它会以插入顺序显示项目。
#3楼
HashMap
is unordered per the second line of the documentation: 根据文档的第二行, HashMap
是无序的:
This class makes no guarantees as to the order of the map; 这个类不保证地图的顺序; in particular, it does not guarantee that the order will remain constant over time. 特别是,它不保证订单会随着时间的推移保持不变。
Perhaps you can do as aix suggests and use a LinkedHashMap
, or another ordered collection. 也许你可以像aix建议的那样使用LinkedHashMap
或其他有序集合。 This link can help you find the most appropriate collection to use. 此链接可以帮助您找到最合适的集合。