Iterator 迭代器进行list 的 add 或者remove 操作:
public static void main(String[] args) {
Person person1 = new Person();
Person person2 = new Person();
Person person3 = new Person();
person3.setName("c");
person2.setName("b");
person1.setName("a");
List<Person> list = new ArrayList<>();
list.add(person1); list.add(person2); list.add(person3);
Iterator<Person> iterator = list.iterator();
while (iterator.hasNext()){
if(iterator.next().getName().equals("a")){
iterator.remove();
}
}
for(Person p:list){
System.out.println(p.getName());
}
}
当然也可以使用倒叙for循环的方法:(不优雅)
public static List reverseorRemove(List list, Object element) {
for (int i = list.size() - 1; i >= 0; i--) {
if (element.equals(list.get(i))) {
list.remove(i);
}
}
return list;
}
注意:不能在增强 for循环或者 forEach 内使用 add 或者 remove 操作,会报错:java.util.ConcurrentModificationException