Java LinkedHashMap 中的 entrySet() 是否也保证顺序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1190083/
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-12 00:41:17  来源:igfitidea点击:

Does entrySet() in a LinkedHashMap also guarantee order?

javalinkedhashmap

提问by Diego

I am using a linkedHashMap to guarantee order when someone tries to access it. However, when it comes time to iterate over it, does using entrySet() to return key/value pairs guarantee order as well? No changes will be made while iterating.

当有人尝试访问它时,我正在使用 linksHashMap 来保证顺序。但是,当需要对其进行迭代时,使用 entrySet() 返回键/值对是否也能保证顺序?迭代时不会进行任何更改。

EDIT:Also, are there any adverse effects from iterating through the map by iterating through its keys and calling get?

编辑:另外,通过遍历映射的键并调用 get 来遍历映射是否有任何不利影响?

采纳答案by Michael Myers

According to the Javadocs, yes.

根据Javadocs,是的。

This implementation differs from HashMapin 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).

此实现的不同之处HashMap在于它维护一个贯穿其所有条目的双向链表。这个链表定义了迭代顺序,通常是将键插入到映射中的顺序插入顺序)。

As for the edit, no, it should work just fine. But the entry set is somewhat faster since it avoids the overhead of looking up every key in the map during iteration.

至于编辑,不,它应该可以正常工作。但是条目集稍微快一些,因为它避免了在迭代期间查找映射中每个键的开销。

回答by Robert

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

这个链表定义了迭代顺序,这通常是键被插入到映射中的顺序(插入顺序)。请注意,如果将键重新插入到映射中,则插入顺序不会受到影响。(如果当 m.containsKey(k) 在调用之前立即返回 true 时调用了 m.put(k, v),则键 k 被重新插入到映射 m 中。)

回答by Daniel F. Thornton

If you're sure no changes will be made during the iteration, then proper ordering with entrySet()is guaranteed, as stated in the API.

如果您确定在迭代期间不会进行任何更改,则entrySet()可以保证正确排序,如API中所述。