HashMap 源码分析 -- entrySet()

HashMap extends AbstractMap implements Map

AbstractMap implements Map

AbstractMap已经实现了map里的一些公共的接口,比如
size(),isEmpty() 等。在AbstractMap里留下了一个abstract 方法

public abstract Set<Entry<K,V>> entrySet()

HashMap 实现只是简单的new EntrySet

public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

HashMap的成员类-EntrySet

final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size(){ return size; }
        public final void clear() { HashMap.this.clear(); }
        //构造函数里new EntryIterator()
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
       ...
}

HashMap的又一个成员类-EntryIterator extends HashIterator

final class EntryIterator extends HashIterator
        implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() {
          return nextNode(); 
        }
    }

HashMap里定义的abstract class HashIterator

  abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

HashIterator() {
            expectedModCount = modCount;
            //table 是HashMap里的数组容器,很关键的一步
            //transient Node<K,V>[] table;

            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { 
            //直到table[index]不为空,将 table[index]付给next
            //也就是next是Node<K,V>
            //Node<K,V> implements Map.Entry<K,V>
            //因此下面的Iterator<Map.Entry<String,String>>里的
            //泛型是Map.Entry<String,String>
           do {} while
            (index < t.length && (next = t[index++]) == null);
            }
        }
        ....
}

调用map的entrySet()来遍历

Map<String, String> map = new HashMap<String, String>();
        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        Set<Map.Entry<String, String>> mapSet = map.entrySet();
        Iterator<Map.Entry<String,String>> it = mapSet.iterator();
        while(it.hasNext()){
            Map.Entry<String,String> entry = it.next();
            System.out.println(entry.getKey() + " = " +entry.getValue());
        }
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页