Java HashMap.entrySet遍历

HashMap通过get方法只能得到value,如何遍历HashMap,访问所有的key和value
transient Set> entrySet;
entrySet是一个set,内部数据是Map.Entry,即是HashMap中key-value
1、获取到entrySet
    public Set> entrySet() {
        Set> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }
2、EntrySet是HashMap内部类
final class EntrySet extends AbstractSet> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry) o;
            Object key = e.getKey();
            Node candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry e = (Map.Entry) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }
        public final Spliterator> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer> action) {
            Node[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                // Android-changed: Detect changes to modCount early.
                for (int i = 0; (i < tab.length && modCount == mc); ++i) {
                    for (Node e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }
由EntrySet的方法可以看到,可以直接操作table数组,清空,删除等
3、iterator方法
 public final Iterator> iterator() {
            return new EntryIterator();
        }
返回一个创建的EntryIterator对象
    final class EntryIterator extends HashIterator
        implements Iterator> {
        public final Map.Entry next() { return nextNode(); }
    }
next的实现是:首先顺序遍历链表,当链表结束收,index++,遍历table数组中下一个链表,一直到遍历结束。
abstract class HashIterator是一个抽象类,内部提供了hasNext,nextNode方法,可以通过iterator.next()获取下一个节点Node,通过iterator遍历HashMap,entrySet支持foreach方法。

你可能感兴趣的:(java)