总结遍历List时删除元素

来源:互联网 发布:文字解密软件 编辑:程序博客网 时间:2024/06/04 19:26

遍历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();}}


原创粉丝点击