JDK源码学习(4)-HashMap的遍历方式,两种迭代器源码分析

对HashMap本身没有迭代器,如果要对HashMap遍历有两种方式。

  1. keySet()方法获取包含key的set对象,调用该对象的迭代器对key值遍历。
  2. entrySet()方法获取包含Map.Entry的set对象,调用该对象的迭代器对Entry实例遍历。
    如:
Map map = new HashMap();
map.put("a1", "a11");
map.put("a2", "a22");
Set set = map.keySet();
for(Iterator iter= set.iterator();iter.hasNext();){
     String key = (String)iter.next();
     String value = (String)map.get(key);
     System.out.println(key);
     System.out.println(value);
}

Set set2 = map.entrySet();
for(Iterator iter = set2.iterator();iter.hasNext();){
     Map.Entry entry =     (Map.Entry)iter.next();
     System.out.println(entry.getKey());
     System.out.println(entry.getValue());
}

这通过KeySet()方法和entrySet()方法获得的对象的迭代器都继承同一个类HashIterator。

 private abstract class HashIterator<E> implements Iterator<E> {
        Entry next;        // next entry to return
        int expectedModCount;   // For fast-fail
        int index;              // current slot
        Entry current;     // current entry

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Entry nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            current = e;
            return e;
        }

可以看出通过keySet()和entrySet()获取对象的跌代方式都类似。只有next()方法不一样,keySet()的迭代器的next只需要key值,多一步getKey的操作,所以效率要低一些。

    private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
        public Map.Entry next() {
            return nextEntry();
        }
    }
    private final class KeyIterator extends HashIterator<K> {
        public K next() {
            return nextEntry().getKey();
        }
    }

在对HashMap进行迭代遍历的时候需要注意一点,在nextEntry() 方法中有一段代码:

            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

modCount这个变量用来记录的HashMap的修改次数,每次修改操作这个值都会增加。在使用新建迭代器的时候这个值会赋值给expectedModCount,每次遍历取下一个值都会判断这个值是否改变,如果改变了就抛出异常,也就是说在对HashMap使用迭代器遍历时不能同时对hashMap进行修改操作,这个控制能起到一定的安全保护作用。

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

你可能感兴趣的:(JDk源码学习)