Java 的 LinkedHashMap 是否维护键的顺序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3478061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:08:06  来源:igfitidea点击:

Does Java's LinkedHashMap maintain the order of keys?

javamapsetlinkedhashmap

提问by Armand

When LinkedHashMap.keySet() is called, will the order of the Set returned be the same as the order the keys were added in?

调用 LinkedHashMap.keySet() 时,返回的 Set 的顺序是否与添加键的顺序相同?

回答by Tom Tresansky

Yes.

是的。

See: LinkedHashMap:

请参阅:LinkedHashMap

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

这个链表定义了迭代顺序,这通常是键被插入到映射中的顺序(插入顺序)。

and from the HashMap#keySetdocumentation:

来自HashMap#keySet文档:

The set [returned] is backed by the map, so changes to the map are reflected in the set, and vice-versa.

set [returned] 由 map 支持,因此对 map 的更改会反映在 set 中,反之亦然。

回答by relet

Yes. The exception is that when a key is reinserted, it appears in the order in which it was first inserted to the list.

是的。唯一的例外是当一个键被重新插入时,它会按照它第一次插入列表的顺序出现。