List 迭代过程中删除或添加元素

[size=medium]1. List 迭代过程中删除元素采用[color=red]list.remove(obj)[/color]会造成其size自减,[color=red]modCount[/color]自增而产生问题:[/size]


Collection list = new ArrayList();
list.add("creek");
list.add("misty");
list.add("forest");

Iterator iter = list.iterator();

while (iter.hasNext()) {
Object obj = iter.next();
if ("creek".equals(obj))
list.remove(obj);
}


运行时会报[color=red]java.util.ConcurrentModificationException[/color]错误。

我们先看看java.util.ArrayList的相关代码:


private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}


还有java.util.AbstractList的:


int expectedModCount = modCount;

public boolean hasNext() {
return cursor != size();
}

public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}


当调用iterator()方法的时候,expectedModCount = modCount (等于3,三次添加元素)
第一次循环的时候,把第一个元素给删除了,这时modCount++ (等于4)
第二次调用iter.next()会调用checkForComodification()方法,check到这两个值不相等,所以报异常。

如果我们需要在迭代的过程中对元素进行删除操作,使用AbstractList提供的remove()方法,当然这也不是线程安全的:


public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();

try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
// Let the values of the two variables be equal
// so that the check would be passed
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}


可以看到这里的expectedModCount已经设置成和modCount相等了。

另一种方式是利用并发库里的CopyOnWriteArrayList类:

Collection list = new CopyOnWriteArrayList();
...


[size=medium]2. List 迭代过程中添加元素采用[color=red]list.add(obj)[/color]会造成其size自增,[color=red]modCount[/color]自增而产生问题,这里就不再赘述。[/size]

你可能感兴趣的:(java,collection)