迭代器遍历集合元素

List集合用迭代器遍历元素的同时为什么不能用集合删除元素,但是可以删除倒数第二个元素

一、如下:

/**
 * ClassName: em01
 * Description:
 * date: 2020/11/5 9:17
 *
 * @author Luo
 * @since JDK 1.8
 */
public class em01 {
    public static void main(String[] args) {
        List<String> a=new ArrayList<String>();
        a.add("1");
        a.add("2");
        a.add("3");
        a.add("4");
        a.add("5");
        a.add("6");
        a.add("7");
        a.add("8");
        a.add("9");
        Iterator<String> it= a.iterator();
        while(it.hasNext()){
            String temp = it.next();//报异常
            if("8".equals(temp)){
//               a.remove(temp); 34行 [1,2,3,4,5,6,7,8]
                 it.remove();//34行[1,2,3,4,5,6,7,8,9]
            }
            System.out.println(temp);
        }
        System.out.println(a);//[1,2,3,4,5,6,7,8,9]

    }
}

1.删除其它元素时,报错的是next()方法位置

1.1 因为modCout!=expectedModCount导致throw new ConcurrentModificationException();
  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() {
    //modCount(记录了对集合修改的次数)
    //expectedModCount(通过迭代器对集合修改的次数)的值会抛异常。
           if ( modCount!= expectedModCount)
               throw new ConcurrentModificationException();
        }

删除倒数第二个元素

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值