当前位置:   article > 正文

HashMap 源码分析 -- entrySet()_map entryset源码

map entryset源码

HashMap extends AbstractMap implements Map

AbstractMap implements Map

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

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

HashMap 实现只是简单的new EntrySet

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

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();
        }
       ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

final class EntryIterator extends HashIterator
        implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() {
          return nextNode(); 
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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);
            }
        }
        ....
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

调用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());
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/306638
推荐阅读
相关标签
  

闽ICP备14008679号