java list 迭代 删除_List 迭代过程中删除或添加元素

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

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);

}

运行时会报java.util.ConcurrentModificationException错误。

我们先看看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();

...

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

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-04-04 21:54

浏览 4202

评论

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值