@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Student {
private String name;
private String age;
}
public static void main(String[] args) {
iteratorDelete();
// listDelete();
}
/**
* list.remove()删除会报错
*/
private static void listDelete() {
List<Student> cityList = setValue();
System.out.println(cityList.size());
for (Student student : cityList) {
if(student.getAge().equals("xx")){
cityList.remove(student);
}
}
System.out.println(cityList.size());
}
/**
* list删除数据使用迭代器删除
*/
private static void iteratorDelete() {
List<Student> cityList = setValue();
ListIterator<Student> iterator =cityList.listIterator();
while (iterator.hasNext()) {
Student student = iterator.next();
if(student.getAge().equals("xx")){
System.out.println("删除的是集合的数据,对iterator没有影响");
iterator.remove();
}
System.out.println("删除后的长度:"+cityList.size());
int i = iterator.nextIndex();
int previousIndex = iterator.previousIndex();
System.out.println(student + "==" + i + "==" + previousIndex);
}
System.out.println(cityList.size());
}
private static List<Student> setValue(){
List<Student> cityList = new ArrayList<Student>();
cityList.add(new Student("xx", "xx"));
cityList.add(new Student("qq", "qq"));
cityList.add(new Student("ww", "ww"));
cityList.add(new Student("ee", "ee"));
cityList.add(new Student("rr", "rr"));
cityList.add(new Student("tt", "tt"));
return cityList;
}
List删除集合元素
最新推荐文章于 2024-06-23 15:11:07 发布
本文探讨了如何在Java中使用`Student`类,展示了`listDelete()`和`iteratorDelete()`方法,对比了list的remove()与迭代器删除元素的区别。通过实例代码,理解了迭代器在避免列表修改错误中的作用。
摘要由CSDN通过智能技术生成