List 删除指定元素

由于jdk 1.5推出了快速便利 for each,我们在编码过程中便利都是for each , 格式如下

for(Object o : objList)
{
    ...
}

现在的场景是,需要删除objList中的某几个元素,自然而然,我们会习惯性的写下如下语句:

int i = 0;
for(Object o : objList)
{
    if(o == value)
   {
       objList.remove(i); 
   }
   i++;
}

这时你就会发现报  java.util.ConcurrentModificationException 异常,此异常是迭代器抛出的异常,官方说明是:

The Iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove  method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
大概意思是:在用迭代器迭代集合的时候,迭代器一旦创建,就不允许更改集合,如果所迭代的集合(Set或者List)的有修改的话,就会抛出 
ConcurrentModificationException异常, 用迭代器自身的remove方法除外...

进一步说明如下:
用for-each遍历 实际上使用的是Iterator迭代器
Iterator的工作机制:
Iterator是工作在一个独立的线程中,并且拥有一个 mutex锁,就是说Iterator在工作的时候,是不允许被迭代的对象被改变的。Iterator被创建的时候,建立了一个内存索引表(单链表),这 个索引表指向原来的对象,当原来的对象数量改变的时候,这个索引表的内容没有同步改变,所以当索引指针往下移动的时候,便找不到要迭代的对象,于是产生错 误。List、Set等是动态的,可变对象数量的数据结构,但是Iterator则是单向不可变,只能顺序读取,不能逆序操作的数据结构,当 Iterator指向的原始数据发生变化时,Iterator自己就迷失了方向。

那么要删除指定的元素应该如何呢?下面是一些解决方法:

一.  用一个List 记录要删除的数据,最后removeAll(List);
List<Integer> removeList = new ArrayList()
for(Integer i : intList)
{
    if(i == 13)
    {
        removeList.add(i);
    }
}
//最后
if(removeList.size()>0)
{
    intList.removeAll(removeList);
}

二.用for循环遍历,原始书写方式
for(int i = 0; i < intList.size(); i++)
{
    if(intList.get(i) == 13)
    {
        intList.remove(i);
        
        //此时要注意,因为list会动态变化不像数组会占位,所以当前索引应该后退一位
        i--;
    }
}

三.用迭代器自带的remove方法,这也是官方推荐的方法
Iterator <Integer> it = intList.iterator();
while(it.hasNext())
{
    if(it.next() == 13)
    {
        it.remove();
    }
}



  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值