简体   繁体   English

LinkedHashMap的集合(值)是否保留插入顺序?

[英]Does a collection (values) from LinkedHashMap preserve the insertion order?

Let's say I have a LinkedHashMap<String, Double> myMap which I added pair1 , pair2 , pair3 pairs to. 假设我有一个LinkedHashMap<String, Double> myMap ,其中添加了pair1pair2pair3对。

And now I do the following loop : 现在,我执行以下循环:

for (Double currDouble : myMap.getValues()) {...}

Would the First Double object in the loop be the one of pair1 ? 循环中的第一个Double对象是否是pair1的一个? And second of pair2 ? 还有pair2第二个? Or it doesn't have to be? 还是不一定要?

I checked with similar program and It seems that it does keep insertion order, but Would that always be the case? 我检查了类似的程序,看来它确实保持插入顺序,但是否总是这样?

By default the LinkedHashMap preserves the insertion order. 默认情况下, LinkedHashMap保留插入顺序。 Though there is an option to switch over to access order which might have been the confusing factor. 尽管可以选择切换到访问顺序,这可能是造成混乱的因素。

So to answer your question, yes , the first Double will be from pair1 and the second from pair2 etc. Given the fact that you didn't set the LinkedHashMap to access order. 因此,要回答您的问题, 是的 ,第一个Double是来自pair1 ,第二个是pair2pair2 。鉴于您没有将LinkedHashMap设置为访问顺序。

If you are still not sure about the behavior, you can always test it by adding a bunch of data to a LinkedHashMap , and iterate over it like you described in your question. 如果仍然不确定该行为,则可以始终通过向LinkedHashMap添加一堆数据来对其进行测试,并按照问题中的描述对其进行迭代。 You'll see that it will preserve insertion order (or access order if set). 您会看到它将保留插入顺序(或访问顺序,如果已设置)。

Yes! 是!

From the first sentence of the LinkedHashMap documentation: ... implementation of the Map interface, with predictable iteration order.... which is normally the order in which keys were inserted into the map (insertion-order). 从LinkedHashMap文档的第一句话开始:...实现Map接口,具有可预测的迭代顺序...。通常是将键插入到映射中的顺序(插入顺序)。

If a key is reinserted ( possibly with a different value ) it doesn't change the original order. 如果重新插入键(可能具有不同的值),则不会更改原始顺序。

See Java Class that implements Map and keeps insertion order? 看到实现Map并保持插入顺序的Java类吗?

You could just do: 您可以这样做:

for (String key : myMap.getKeys())
  Double d = myMap.get(key);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM