使用 values() 方法从 LinkedHashMap 获取条目的 LinkedList
Get LinkedList of entries from LinkedHashMap with values() method
我正在尝试了解是否可以从链接的哈希映射中获取条目的链接列表。我可以获得 entrySet()
,然后使用迭代器遍历插入顺序中的每个条目。这将给我插入顺序中条目的链接列表。
我用values()
的方法能保证结果一样吗?
我也这么认为。在内部 class 使用 java.util.LinkedHashMap.LinkedHashIterator
,entrySet()
和 values()
都使用它,因此如果前者允许您按插入顺序迭代,后者将执行相同的操作.
Can I guarantee the same result if I use the values()
method?
基本上,LinkedHashMap#values
returns 你对内部结构的看法是有限的。我敢说它 必须 给出相同的结果。文档中没有明确说明
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.
但突出显示的摘录让我这么认为。
"The same result" 不仅仅是一个数据集合:它包括数据迭代的方式(迭代器)。 "changes to the map are reflected in the set" 对我来说意味着两个迭代器共享一个算法,该算法在同一块数据上会导致相同的行为。
截至Java8,让我们看一下LinkedHashMap
. We can deduct the internal behavior from the entrySet()
and values()
方法定义的来源:
- 第 627 行的方法
entrySet()
returns new LinkedEntrySet()
从第 634 行起使用 new LinkedEntryIterator()
作为迭代器。
- 第 581 行上的方法
values()
returns new LinkedValues()
从第 588 行起使用 new LinkedValueIterator()
作为迭代器。
现在,让我们看看在同一个文件中从第 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(); }
}
它们都扩展了 LinkedHashIterator
,这意味着使用 entrySet()
and values()
.
将以相同的方式处理映射值的访问
我正在尝试了解是否可以从链接的哈希映射中获取条目的链接列表。我可以获得 entrySet()
,然后使用迭代器遍历插入顺序中的每个条目。这将给我插入顺序中条目的链接列表。
我用values()
的方法能保证结果一样吗?
我也这么认为。在内部 class 使用 java.util.LinkedHashMap.LinkedHashIterator
,entrySet()
和 values()
都使用它,因此如果前者允许您按插入顺序迭代,后者将执行相同的操作.
Can I guarantee the same result if I use the
values()
method?
基本上,LinkedHashMap#values
returns 你对内部结构的看法是有限的。我敢说它 必须 给出相同的结果。文档中没有明确说明
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.
但突出显示的摘录让我这么认为。
"The same result" 不仅仅是一个数据集合:它包括数据迭代的方式(迭代器)。 "changes to the map are reflected in the set" 对我来说意味着两个迭代器共享一个算法,该算法在同一块数据上会导致相同的行为。
截至Java8,让我们看一下LinkedHashMap
. We can deduct the internal behavior from the entrySet()
and values()
方法定义的来源:
- 第 627 行的方法
entrySet()
returnsnew LinkedEntrySet()
从第 634 行起使用new LinkedEntryIterator()
作为迭代器。 - 第 581 行上的方法
values()
returnsnew LinkedValues()
从第 588 行起使用new LinkedValueIterator()
作为迭代器。
现在,让我们看看在同一个文件中从第 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(); }
}
它们都扩展了 LinkedHashIterator
,这意味着使用 entrySet()
and values()
.