关于 HashMap 集合的 keySet() 方法


Map<K, V> map = HashMap<K, V>();
Set<K> keySet = map.keySet(); //'map' is  parameter of HashMap object
Iterator<K> keyIterator = keySet.iterator();

我正在研究如何通过"迭代器"获取密钥。上面的代码是其中的一部分。

但是[Set<K> keySet = map.keySet();]<-在这一部分中

HashMapkeySet()方法不是Set接口的keySet()方法在HashMap中重新定义的吗?

但我在 JAVA API 文档的方法菜单中找不到它。

你似乎使这变得比必要的更复杂。

Map<K,V> 有一些键;它会以 Set的形式提供这些键的视图。

该 Set<>必须实现 Set<> 接口,该接口具有 Iterable<> 作为子接口。 因此,您可以在 Set 上获取一个迭代器。

由于它是一个迭代器,那么如果你迭代它,它最终会产生每个可能的键。 那是:

while (iterator.hasNext()) {
key = iterator.Next(); // <<< this is the key
:
}

但你到底想做什么?

我正在研究如何通过上面的"迭代器"获取密钥是 那

Map 和 Set 接口的要点是您可以通过密钥直接访问它们。

keySet()方法返回类型为KeySetHashMap中的一组键。HashMap 中的内部实现实现AbstractSet并将键存储到名为keySet的集合中。

HashMap中实现的层次结构:

|---- Collection<E> extends Iterable<E>
|
|------- Set<E> extends Collection<E>
|
|------------ AbstractSet<E> extends AbstractCollection<E> implements Set<E>
|
|--------------- KeySet extends AbstractSet<K>

你当然可以这样做。 但我从来没有需要得到keySet迭代器。 您可以执行以下操作。

Map<String, Object> map = new HashMap<>();
// later
for (String key : map.keySet()) {
// so something with keys (e.g) print them.
System.out.println(key);
}

但你也可以这样做。

Iterator<String> it = map.keySet().iterator();
while(it.hasNext()) {
System.out.println(it.next());
} 

最新更新