【发布时间】:2018-12-28 08:31:42
【问题描述】:
这是 java.util.HasMap 类中的 keySet() 函数:
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
在评论中,它说这个功能
返回此映射中包含的键的 {@link Set} 视图。 该集合由地图支持,因此对地图的更改是 反映在集合中,反之亦然。
因此,我希望这个函数返回的 KeySet 类型的对象将包含对“键视图”的引用。 但是,当我查看代码时,KeySet 类根本不包含任何字段,它的所有超类也不包含。
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
谁能解释一下
- “按键视图”是什么意思?什么样的数据是“视图”?
- HashMap.keySet() 如何使用根本不包含任何引用的 KeySet 对象返回键的视图?
为了更清楚:
这是一个打印出键集值的代码示例。虽然 KeySet 对象持有对包含地图数据的引用,但这怎么能准确地输出关键数据而不是地图的其他数据(不是值数据或其他任何数据)。是什么告诉这个 KeySet 对象只保存 MapKeys?我在它的代码中看不到这样的指令。
package com.tutorialspoint;
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
// create hash map
HashMap newmap = new HashMap();
// populate hash map
newmap.put(1, "tutorials");
newmap.put(2, "point");
newmap.put(3, "is best");
// get keyset value from map
Set keyset = newmap.keySet();
// check key set values
System.out.println("Key set values are: " + keyset);
}
}
输出:
键集值为:[1, 2, 3]
【问题讨论】:
-
顺便说一句,你的
HashMapDemo使用raw types,你应该避免。在此处使用HashMap<Integer, String>和Set<Integer>。
标签: java memory hashmap inner-classes keyset