List中remove数据

List中remove数据的正确使用方法

 private void removeDuplication(List<Integer> data){
		if(data == null || data.size()<=0){
			return;
		}
		
		Iterator<Integer> it = data.iterator();  
	    while(it.hasNext()){  
	    	Integer str = it.next();  
	        if(str.equals(2)){  
	        	it.remove(); 
	        }  
	     }
	}
private void remove(List<Integer> data){
		for (int i = data.size()-1; i >= 0; i--) {
			int item = data.get(i);
			if(item == 2 || item == 3){
				data.remove(i);
			}
		}
		System.out.println(data);
	}

List中remove数据的错误使用方法

1,

ArrayList<Integer> data= new ArrayList<Integer>();
	data.add(1);
	data.add(2);
	data.add(3);
	data.add(4);
	data.add(5);
	data.add(5);

private void remove(List<Integer> data){
		for (int i = 0; i < data.size(); i++) {
			int item = data.get(i);
			if(item == 2 || item == 3){
				data.remove(i);//只能remove 2,不能移除相邻的两个数
			}
		}
		System.out.println(data);

2,

private void removeDuplication(List<Integer> data){
		if(data == null || data.size()<=0){
			return;
		}
		
		Iterator<Integer> it = data.iterator();  
	    while(it.hasNext()){  
	    	Integer str = it.next();  
	        if(str.equals(2)){  
	        	data.remove(str); //报错  throw new ConcurrentModificationException();
	        }  
	     }
		
	}

错误代码分析

错误1:源码如下
移除数据之后,之后的数据左移。也就是被移除的index的位置被index+1 占据了,for循环接下来从index+2(相对于原始数据)的数据开始

public E remove(int index) {
        rangeCheck(index);
        modCount++;
        E oldValue = elementData(index);
        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

        return oldValue;
    }

错误2:源码如下
modCount 是AbstractList内部变量,它代表该List对象被修改的次数,每对List对象修改一次,modCount都会加1。
Itr类里有一个成员变量expectedModCount,它的值为创建Itr对象的时候List的modCount值。用此变量来检验在迭代过程中List对象是否被修改了,如果被修改了则抛出java.util.ConcurrentModificationException异常。

增加modCount变量 主要是防止线程的异步问题。防止在list在遍历的时候,数据被其他线程修改。

final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值