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);
}
}
版权归属:
叶子
本文链接:
https://www.benbenye.top/archives/java-yi-ge-list-ji-he--xun-huan-shan-chu-mou-ge-yuan-su-wen-ti
许可协议:
本文使用《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》协议授权
评论区