问题描述
据我所知,要迭代 Map
,我需要使用 entrySet()
方法然后使用结果 Set
上的 Iterator
。我觉得问题可能很愚蠢,但是, Map
是如何完全实现的,以便直接使用 Iterator
是不可能的?据我所知, Map
不是一个集合, Iterator
是用于集合的。但从逻辑上讲,不是 Map
也是一个键值对的集合(虽然它没有实现集合
接口)?
I understand that to iterate through a Map
, I need to use the entrySet()
method and then use the Iterator
on the resultant Set
. I feel the question might be silly, but, how is the Map
exactly implemented so that using an Iterator
on it directly isn't possible? As far as I understand, Map
isn't a collection, and Iterator
is meant to be used over a collection. But logically, isn't Map
also a collection of key-value pair(though it doesn't implement the Collection
interface)?
推荐答案
AFAIK,您不能直接迭代Map,因为Map支持三种类型的迭代并没有明确的理由选择其中一个。做等效的 entrySet()。iterator()
可能是合理的,但这不是做出的选择。
AFAIK, You can't iterate over a Map directly because there are three types of iteration that a Map supports and there was no clear reason to choose one of the other. Doing the equivalent entrySet().iterator()
may have been reasonable, but it's not the choice which was made.
这篇关于为什么我们不能在Map(Java)上使用Iterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!