Iterator迭代器使用注意事项

1、Iterator迭代器

我们在平常经常会使用到foreach,for关键字,其实他们的内部原理使用的都是Iterator迭代器的原理。 但是在使用的时候需要注意的是,如果在遍历的过程中增加元素、删除元素等改变了List、HashMap之类的List的结构时,会产生ConcurrentModificationException(并发修改)异常。

2、分析

我们使用HashMap来分析,先看下面的一段代码:

HashMap<String, String> map = new HashMap<>();
map.put("1", "111");
map.put("2", "222");
map.put("3", "333);
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()) {
    Map.Entry<String, String> entry = iterator.next(); //这里会引发ConcurrentModificationException异常
    String key = entry.getKey();
    String value = entry.getValue();
    if(value.equals("111") {
        map.remove(key); 
        //map.put("444");
    }
}
复制代码

从引发异常的代码行跟踪进去,进入到HashMap的HashIterator类,该类实现了Iterator接口。而next()方法最终会执行到nextEntry()方法。看一下nextEntry()方法的实现:

final Entry<K,V> nextEntry() {
	if (modCount != expectedModCount)
		throw new ConcurrentModificationException();
	HashMapEntry<K,V> e = next;
	if (e == null)
		throw new NoSuchElementException();

	if ((next = e.next) == null) {
		HashMapEntry[] t = table;
		while (index < t.length && (next = t[index++]) == null)
			;
	}
	current = e;
	return e;
}
复制代码

可以看到抛出异常的原因是modCount != expectedModCount。modCount是HashMap中的一个变量,当HashMap结构改变时(比如put进去了一个新的元素,删除了一个新的元素等),这个modCount记录的是改变的次数,而expectedModCount是HashIterator类对象的一个变量,在HashIterator构造函数中赋值,如下所示:

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

上面的expectedModCount = modCount即为赋值语句。 返回上面举的例子,当我们在遍历HashMap时删除了一个元素,即map.remove(key); 最终执行removeEntryForKey(key)方法,在该方法中执行了modCount++,也即modCount的值改变了。当在HashIterator中继续往下执行到nextEntry()方法时,由于modCount的值不等于expectedModCount,那么就抛出了ConcurrentModificationException异常。

3、为什么不相等就抛出异常

我们发散一下,如果将if (modCount != expectedModCount)这句判断语句去掉呢? 来看一种情况,还是用上面的remove(key)作为例子,如果这个key刚好是下一个需要访问到的key呢?顺着nextEntry()看下来:

final Entry<K,V> nextEntry() {
        ...省略
	HashMapEntry<K,V> e = next;
        ...省略
	if ((next = e.next) == null) {
		HashMapEntry[] t = table;
		while (index < t.length && (next = t[index++]) == null)
			;
	}
	current = e;
	return e;
}
复制代码

我们将异常的情况去掉。这个时候next就是我们之前删除掉的entry,这个entry.next为空,进入if语句块,if语句块要做的事情是,从index开始寻找下一个不为空的元素。而index的值是entry还没有被删除时所处的位置。说起来听抽象的,还是看图说话好了:

例如,我们在遍历的时候删除了3号的元素,这个时候index指向了下一个元素,即index=3。当我们继续执行nextEntry时,由于hasMap改变了,也即table改变了,那么下次访问到就是5号的元素,也就是说4号元素完全没有被我们访问到,所以这是有问题的。所以Java规定了如果HashMap的结构发生了变化,那么就抛出并发修改异常。

4、怎么在遍历时增加或者删除元素?

上面分析了既然在遍历时不允许删除HashMap的元素,那么我们有什么样的方法删除或者添加吗?因为我们在工作时肯定会遇到这样的问题的。 对于删除,我们可以看到Iterator有一个remove()的方法。而HashIterator的remove()方法如下:

public void remove() {
	if (current == null)
		throw new IllegalStateException();
	if (modCount != expectedModCount)
		throw new ConcurrentModificationException();
	Object k = current.key;
	current = null;
	HashMap.this.removeEntryForKey(k);
	expectedModCount = modCount;
}
复制代码

可以看到在这里通过调用HashMap的removeEntryForKey删除了当前的元素,并且同步地将expectedModCount修改为modCount,所以下次执行nextEntry()方法时就不会报并发修改异常了。

上面的情况只是在单线程不会出问题,但是如果在多线程下,即使使用了remove()方法,也会有可能出现ConcurrentModificationException错误。所以在多线程下为了保证现场安全,我们需要对要操作的HashMap进行一个加锁操作,这样就可以防止在遍历的过程中有其他现场去修改HashMap的结构,从而导致出现ConcurrentModificationException错误。

那么如果我们想要添加元素呢?好像Iterator只实现了remove()这样一个方法,对于其他操作并没有为我们实现,那么我们就需要自己来实现了:

    LinkedList<Map.Entry<String, String>> tempList = new LinkedList<Map.Entry<String, String>>();
	tempList.addAll(map.entrySet());
	ListIterator<Map.Entry<String, String>> itor = tempList.listIterator();
	Map.Entry entry = null;

	while (itor.hasNext()) {
		 entry = (Map.Entry) itor.next();
		 Object key = entry.getKey();

		 if (key.toString().equals("3")) {
			map.put("33", "33");
		 }
	}
复制代码

我们可以使用一个LinkedList来装载HashMap的entrySet,然后在遍历时修改或者添加map的元素,由于该LinkedList的Iterator和HashMap的Iterator是不同的对象,所以不用担心会引发并发修改异常。

5、文档参考:

www.cnblogs.com/Scott007/p/…

猜你喜欢

转载自juejin.im/post/5d7318b85188250a98581eda