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

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

编辑: 还有,通过遍历 map 的键和调用 get 来遍历 map 有什么不利影响吗?

33694 次浏览

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

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.

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