java-list循环过程中删除元素的三种方式对比。
1.通过 iterator(正确做法)
2.普通for循环(java.util.ConcurrentModificationException 异常)
3.foreach循环(java.util.ConcurrentModificationException 异常)
package com.zhong.jpa_demo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* TestListRemove
*/
public class TestListRemove {
public static void main(String[] args) {
testListIteratorDelete();
testListForDelete();
testListForeachDelete();
}
/**
* 通过 iterator 删除
*/
public static void testListIteratorDelete() {
Listlist = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
Iteratorit = list.iterator();
int i = 0;
while (it.hasNext()) {
System.out.print(it.next());
if (i == 0) {
it.remove();
}
i++;
}
System.out.println();
// System.out.println(list.size());
}
/**
* 普通for 循环删除
*/
public static void testListForDelete() {
Listlist = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
for (int i = 0; i < list.size(); i++) {
if (i == 1) {
list.remove(i); // java.util.ConcurrentModificationException
// 删除特定元素后 break;
}
System.out.print(list.get(i));
}
System.out.println();
}
/**
* foreach 循环删除
*/
public static void testListForeachDelete() {
Listlist = new ArrayList<>();
list.add("x");
list.add("y");
list.add("z");
for (String item : list) {
if (item.equals("z")) {
list.remove(item); // java.util.ConcurrentModificationException
// 删除特定元素后 break;
}
System.out.print(item);
}
System.out.println();
}
}