赞
踩
不要使用for-each遍历,换成迭代器遍历,并且不要用list.remove()方法移除对象,用迭代器的方法iterator.remove()移除对象,具体看下面的代码:
class ArrayListDelete { public static void main(String[] args) { Student student = new Student("小明", "1"); Student student1 = new Student("小明", "2"); Student student2 = new Student("小明", "3"); ArrayList<Student> students = new ArrayList<>(); students.add(student); students.add(student1); students.add(student2); Iterator<Student> iterator = students.iterator(); while (iterator.hasNext()){ Student next = iterator.next(); if(next.getId().equals("1")){ iterator.remove(); } } System.out.println(students.toString()); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。