遍歷刪除List中的元素有不少種方法,當運用不當的時候就會產生問題。下面主要看看如下幾種遍歷刪除List中元素的形式:java
1.經過加強的for循環刪除符合條件的多個元素this
2.經過加強的for循環刪除符合條件的一個元素spa
3.經過普通的for刪除刪除符合條件的多個元素.net
4.經過Iterator進行遍歷刪除符合條件的多個元素對象
- 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 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);
- }