Java中的AbstractMap是个抽象类,提供了一个Map接口的基础实现。其keySet()方法是返回map中所有的key的集合。看了其源码,一头雾水。想知道它是怎么实现的?源码如下:transient volatile Set<K> keySet = null;transient volatile Collection<V> values = null;public Set<K> keySet() { if (keySet == null) { keySet = new AbstractSet<K>() { public Iterator<K> iterator() { return new Iterator<K>() { private Iterator<Entry<K,V>> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public K next() { return i.next().getKey(); } public void remove() { i.remove(); } }; } public int size() { return AbstractMap.this.size(); } public boolean isEmpty() { return AbstractMap.this.isEmpty(); } public void clear() { AbstractMap.this.clear(); } public boolean contains(Object k) { return AbstractMap.this.containsKey(k); } }; } return keySet;}
添加回答
举报
0/150
提交
取消