为什么ArrayList删除数据的时候不建议使用remove方法

        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");

        for (String string : list) {
            if ("e".equals(string)){
                list.remove(string);
            }
        }

当删除“e”时会报错java.util.ConcurrentModificationException,这是因为forEach循环,查看class文件可知

	Iterator iterator = list.iterator();
	while(iterator.hasNext()) {
		String s;
		if((s = (String) iterator.next()).equals("e")) {
			list.remove(s);
		}
	}

问题就在iterator.next(),查看源码

//当删除e时,size为5,curse为4.而删除5后size为4,curse为5还会进入循环体。
public boolean hasNext() {
            return cursor != size;
        } 

public E next() {
            checkForComodification();//校验修改次数是否和预期修改次数一致
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }


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

又因为ArrayList的remove方法只修改modCount,而没修改expectedModCount。

    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

 private void fastRemove(int index) {
        modCount++;//在此修改modCount
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

正确的写法应该为

Iterator iterator = list.iterator();
while(iterator.hasNext()) {
	String s;
	if((s = (String) iterator.next()).equals("e")) {
          iterator.remove();
	}
}
 public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;//同步预期修改次数
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值