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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值