一、Java 循环删除list中指定元素
增强for循环删除指定元素
@Test
public void test(){
String[] strs={"a", "b", "c", "f", "b", "e", "d"};
Listlist = new ArrayList<>(Arrays.asList(strs));
for (String s : list) {
System.out.println("------" + s + "------");
if ("b".equals(s)) {
list.remove(s);
}
}
}
结果:
java.util.ConcurrentModificationException
异常
iterator删除指定元素
@Test
public void test(){
String[] strs={"a", "b", "c", "f", "b", "e", "d"};
Listlist = new ArrayList<>(Arrays.asList(strs));
Iteratoriterator = list.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
System.out.println("------"+next+"------");
if ("b".equals(next)) {
iterator.remove();
}
}
System.out.println(list.toString());
}
CopyOnWriteArrayList
@Test
public void test(){
Listlist = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
CopyOnWriteArrayListcowList = new CopyOnWriteArrayList<>(list);
for (String str : cowList) {
if ("aa".equals(str)) {
cowList.remove(str);
}
}
System.out.println(cowList.size());
}
普通for循环
for (int i = 0; i < list.size(); i++) {
if ("2".equals(list.get(i))) {
list.remove(i);
}
}
有重复元素的删除方法
Listlist = new ArrayList<>();
list.add("a");
list.add("a");
list.add("c");
list.add("d");
list.add("a");
int i=0,size= list.size();
for (; i < size; i++) {
if ("a".equals(list.get(i))) {
list.remove(i);
i-=1;
size-=1;
}
}
for (String str : list) {
log.info(str);
}