Get LinkedList of entries from LinkedHashMap with values() method

ras*_*man 8 java collections dictionary linkedhashmap

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?

Nik*_*las 5

从 Java 8 开始,让我们来看看LinkedHashMap. 我们可以从entrySet()values()方法定义中推导出内部行为:

  • 该方法在第 627 行entrySet()返回new LinkedEntrySet(),该行new LinkedEntryIterator()用作第 634 行的迭代器。
  • 该方法在第 581 行values()返回new LinkedValues(),该行new LinkedValueIterator()用作第 588 行的迭代器。

现在,让我们看看从第 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(); }
}
Run Code Online (Sandbox Code Playgroud)

它们都扩展LinkedHashIterator,这意味着使用entrySet()和以相同的方式访问地图的值values()