侧边栏壁纸
  • 累计撰写 39 篇文章
  • 累计创建 51 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

【Java】一个List集合,循环删除某个元素问题

叶子
2024-07-10 / 0 评论 / 0 点赞 / 82 阅读 / 436 字
package com.example.demo.test.java;

import java.util.ArrayList;
import java.util.Iterator;

public class Test {

  static ArrayList<String> init() {
    ArrayList<String> strings = new ArrayList<>();
    strings.add("1"); strings.add("2"); strings.add("3");
    strings.add("4"); strings.add("5"); strings.add("6"); strings.add("7"); strings.add("8");
    strings.add("9"); strings.add("10"); strings.add("10"); strings.add("11");
    return strings;
  }

  public static void main(String[] args) throws InterruptedException {
    ArrayList<String> list1 = init();
    try {
      list1.forEach((e) -> {
        if ("10".equals(e)) {
          list1.remove(e);
        }
      });
    } catch (Exception ex) {
      System.out.println(">>>>>>>>>>>>>>> forEach 循环删除异常 >>>>>>>>>>>>>>>");
      ex.printStackTrace();
    }

    Thread.sleep(5000L);
    System.out.println();
    System.out.println();
    System.out.println();
    ArrayList<String> list2 = init();
    try {
      for (String e : list2) {
        if ("10".equals(e)) {
          list2.remove(e);
        }
      }
    } catch (Exception ex) {
      System.out.println(">>>>>>>>>>>>>>> 增强 for 循环删除异常 >>>>>>>>>>>>>>>");
      ex.printStackTrace();
    }

    Thread.sleep(5000L);
    System.out.println();
    System.out.println();
    System.out.println();
    ArrayList<String> list3 = init();
    for (int i = 0; i < list3.size(); i++) {
      if ("10".equals(list3.get(i))) {
        list3.remove(list3.get(i));
      }
    }
    System.out.println(">>>>>>>>>>>>>>> for 循环删除正常,但是连续的元素未删除 >>>>>>>>>>>>>>>");
    System.out.println("list3 = " + list3);

    Thread.sleep(5000L);
    System.out.println();
    System.out.println();
    System.out.println();
    ArrayList<String> list4 = init();
    Iterator<String> iterator = list4.iterator();
    while (iterator.hasNext()) {
      if ("10".equals(iterator.next())) {
        iterator.remove();
      }
    }
    System.out.println(">>>>>>>>>>>>>>> Iterator 循环删除正常 >>>>>>>>>>>>>>>");
    System.out.println("list4 = " + list4);


  }

}

image-1720616978329

0

评论区