总结遍历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();}}
阅读全文
0 0
- 总结遍历List时删除元素
- 遍历List时 删除元素
- 遍历List,删除元素
- Java动态 遍历List 时删除List特征元素 异常问题 及解决方式总结
- 遍历List删除元素问题
- List遍历中删除元素
- 遍历删除List中的元素
- 遍历删除List中的元素
- Java动态遍历List 时删除List特征元素
- STL遍历删除元素总结
- HashMap和List遍历方法总结及如何遍历删除元素
- 遍历list或map时删除元素(较巧妙)
- java 遍历list、set时 删除元素 java.util.ConcurrentModificationException
- JAVA中关于遍历List时删除元素的实践
- 遍历list时删除元素的正确做法
- STL中list,遍历删除元素注意事项
- java 遍历 删除元素 List Set
- C# 遍历List 并删除某个元素
- 死锁问题
- 金蝶EAS,调用标准产品登录接口,EASLogin接口调用
- Elasticsearch 架构原理
- = == === != !==的区别
- mysql 中的事务
- 总结遍历List时删除元素
- 【RabbitMQ】三种Exchange模式——订阅、路由、通配符模式
- Ubuntu14.04下安装Tensorflow遇到的问题
- 单例模式的几种写法(包含双检锁写法)
- POJ 3694 Network(Tarjan求割边+LCA)
- c++运算符重载
- C++ 操作EXCEL(OLE/COM)
- extract-text-webpack-plugin 的安装及配置
- ActiveMQ与Kafka对比