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. }  
 
 
原文地址:https://www.cnblogs.com/Pjson/p/8548966.html