遍歷List時候發現問題,查看了別人寫的發現還可以有另外一種解決方法。
http://blog.csdn.net/dongzhouzhou/article/details/15378433
這個鏈接是別人總結的遍歷刪除List元素的方法,
在這裏增加了一種方法每次遍歷都重新實例一個ArraryList就可以了
因爲增加for循環使用迭代器的方法
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
modCount != expectedModCount
保證了迭代器自從創建到遍歷的過程中,集合沒有被修改,如果被修改了就會報出這個異常下面根據這個問題解決方法就是每次迭代都重新實例一下ArrayList,這樣增刪元素就不會有影響了
import java.util.ArrayList;
import java.util.List;
public class listRemoveValid {
class Student {
private int id;
public Student(int id){this.id=id;}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public void listRemove() {
List<Student> students = this.getStudents();
for (Student stu : new ArrayList<Student>(students)) {
System.out.println(stu.id);
if (stu.getId() == 2)
students.remove(stu);
}
System.out.println("刪除後數量:"+students.size());
}
private List<Student> getStudents() {
List<Student> students = new ArrayList<Student>();
students.add(new Student(1));
students.add(new Student(2));
students.add(new Student(3));
students.add(new Student(4));
students.add(new Student(5));
return students;
}
public static void main(String[] args) {
new listRemoveValid().listRemove();
}
}