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());
        }
    原文作者:xiao_long_guo
    原文地址: https://blog.csdn.net/guo_xl/article/details/78536732
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞