zoukankan      html  css  js  c++  java
  • List在遍历中删除t元素

     

    法一:使用普通for循环遍历

    注意: 1.从头开始循环,每次删除后 i  减一。
                2.从尾开始循环。
     
    1. public class Main {  
    2.     public static void main(String[] args) throws Exception {  
    3.         List<Integer> list = new CopyOnWriteArrayList<>();  
    4.         for (int i = 0; i < 5; i++)  
    5.             list.add(i);  
    6.         for (int i = 0; i < list.size(); i++) { 
    7.             System.out.print(i + " " + list.get(i));  
    8.             if (list.get(i) % 2 == 0) {  
    9.                 list.remove(list.get(i));  
    10.                 System.out.print(" delete");  
    11.                 i--; // 索引改变!  
    12.             }  
    13.             System.out.println();  
    14.         }  
    15.     }  
    16. }  
     

    法二:使用增强型for循环遍历

    注意:不使用CopyOnWriteArrayList可以看到删除第一个元素时是没有问题的,但删除后继续执行遍历过程的话就会抛出ConcurrentModificationException的异常。

    原因:因为元素在使用的时候发生了并发的修改,导致异常抛出。但是删除完毕马上使用break跳出,则不会触发报错

    1. public class Main {  
    2.     public static void main(String[] args) throws Exception {  
    3.         List<Integer> list = new CopyOnWriteArrayList<>();  
    4.         for (int i = 0; i < 5; i++)  
    5.             list.add(i);  
    6.         // list {0, 1, 2, 3, 4}  
    7.         for (Integer num : list) {  
    8.             // index and number  
    9.             System.out.print(num);  
    10.             if (num % 2 == 0) {  
    11.                 list.remove(num);  
    12.                 System.out.print(" delete");  
    13.             }  
    14.             System.out.println();  
    15.         }  
    16.     }  
    17. }  

    法三:使用iterator遍历

    注意:使用iterator的remove()而不是list的remove()方法
     
    1. public class Main {  
    2.     public static void main(String[] args) throws Exception {  
    3.         List<Integer> list = new ArrayList<>();  
    4.         for (int i = 0; i < 5; i++)  
    5.             list.add(i);  
    6.         // list {0, 1, 2, 3, 4}  
    7.         Iterator<Integer> it = list.iterator();  
    8.         while (it.hasNext()) {  
    9.             // index and number  
    10.             int num = it.next();  
    11.             System.out.print(num);  
    12.             if (num % 2 == 0) {  
    13.                 it.remove();  
    14.                 System.out.print(" delete");  
    15.             }  
    16.             System.out.println();  
    17.         }  
    18.     }  
    19. }  
     
     
  • 相关阅读:
    npm 默认创建项目如何自动配置
    VueJS + TypeScript 入门第一课
    实现类数组转化成数组(DOM 操作获得的返回元素值是一个类数组)
    webpack4(4.41.2) 打包出现 TypeError this.getResolve is not a function
    vue-cli 4.0.5 配置环境变量样例
    关于H5页面在微信浏览器中音视频播放的问题
    ant-design-vue 快速避坑指南
    记elementUI一个大坑
    VUE自定义(有限)库存日历插件
    node转发请求 .csv格式文件下载 中文乱码问题 + 文件上传笔记
  • 原文地址:https://www.cnblogs.com/Pjson/p/8548966.html
Copyright © 2011-2022 走看看