如何在HashMap中保留插入顺序? [重复]

本文翻译自: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. 此链接可以帮助您找到最合适的集合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值