简体   繁体   中英

Get LinkedList of entries from LinkedHashMap with values() method

I'm trying to understand if I can get a linked list of entries from my linked hash map. I can get entrySet() and then using iterator I get through each entry in the insertion order. This will give me the linked list of entries in the insertion order.

Can I guarantee the same result if I use the values() method?

As of Java 8, let's take a look at the source of LinkedHashMap . We can deduct the internal behavior from the entrySet() and values() method definitions:

  • The method entrySet() returns new LinkedEntrySet() on the line 627 which uses new LinkedEntryIterator() as the iterator as of line 634.
  • The method values() returns new LinkedValues() on the line 581 which uses new LinkedValueIterator() as the iterator as of line 588.

Now, let's look at the sources of those inner classes defined in the very same file beginning from line 737:

final class LinkedValueIterator extends LinkedHashIterator
    implements Iterator<V> {
    public final V next() { return nextNode().value; }
}

final class LinkedEntryIterator extends LinkedHashIterator
    implements Iterator<Map.Entry<K,V>> {
    public final Map.Entry<K,V> next() { return nextNode(); }
}

They both extend LinkedHashIterator which implies the accessing of values of the map would be treated the same way using both entrySet() and values() .

Can I guarantee the same result if I use the values() method?

Basically, LinkedHashMap#values returns you a restricted view of the internal structure. And I'd venture to say it must give the same result. It's not explicitly stated in the docs

Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa .

but the highlighted excerpt makes me think so.

"The same result" is more than a data collection: it includes the way the data should be iterated (the iterator). "changes to the map are reflected in the set" to me implies that both iterators share one algorithm, which, on the same piece of data, would result in the same behaviour.

I think so. Internally the class uses java.util.LinkedHashMap.LinkedHashIterator , which is used by both entrySet() and values() , so if the former allows you to iterate in the insertion order, the latter will do the same.

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