遍历删除List中的元素有很多种方法,当运用不当的时候就会产生问题。下面主要看看以下几种遍历删除List中元素的形式:
1.通过增强的for循环删除符合条件的多个元素
2.通过增强的for循环删除符合条件的一个元素
3.通过普通的for删除删除符合条件的多个元素
4.通过Iterator进行遍历删除符合条件的多个元素
-
-
-
-
-
public void listRemove() {
-
List<Student> students = this.getStudents();
-
for (Student stu : students) {
-
if (stu.getId() == 2)
-
students.remove(stu);
-
}
-
}
-
-
-
-
-
public void listRemove() {
-
List<Student> students = this.getStudents();
-
for (Student stu : students) {
-
if (stu.getId() == 2)
-
students.remove(stu);
-
}
-
}
-
-
-
-
public void listRemoveBreak() {
-
List<Student> students = this.getStudents();
-
for (Student stu : students) {
-
if (stu.getId() == 2) {
-
students.remove(stu);
-
break;
-
}
-
}
-
}
-
-
-
-
public void listRemoveBreak() {
-
List<Student> students = this.getStudents();
-
for (Student stu : students) {
-
if (stu.getId() == 2) {
-
students.remove(stu);
-
break;
-
}
-
}
-
}
-
-
-
-
-
-
-
-
-
-
public void listRemove2() {
-
List<Student> students = this.getStudents();
-
for (int i=0; i<students.size(); i++) {
-
if (students.get(i).getId()%3 == 0) {
-
Student student = students.get(i);
-
students.remove(student);
-
}
-
}
-
}
-
-
-
-
-
-
-
-
-
-
public void listRemove2() {
-
List<Student> students = this.getStudents();
-
for (int i=0; i<students.size(); i++) {
-
if (students.get(i).getId()%3 == 0) {
-
Student student = students.get(i);
-
students.remove(student);
-
}
-
}
-
}
-
-
-
-
public void iteratorRemove() {
-
List<Student> students = this.getStudents();
-
System.out.println(students);
-
Iterator<Student> stuIter = students.iterator();
-
while (stuIter.hasNext()) {
-
Student student = stuIter.next();
-
if (student.getId() % 2 == 0)
-
stuIter.remove();
-
}
-
System.out.println(students);
-
}
-
-
-
-
public void iteratorRemove() {
-
List<Student> students = this.getStudents();
-
System.out.println(students);
-
Iterator<Student> stuIter = students.iterator();
-
while (stuIter.hasNext()) {
-
Student student = stuIter.next();
-
if (student.getId() % 2 == 0)
-
stuIter.remove();
-
}
-
System.out.println(students);
-
}
|