简体   繁体   中英

Does entrySet() in a LinkedHashMap also guarantee order?

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.

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

According to the Javadocs , yes.

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

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.

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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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