遍歷刪除List中的元素有很多種方法,當運用不當的時候就會產生問題。下面主要看看以下幾種遍歷刪除List中元素的形式:
1.通過增強的for循環刪除符合條件的多個元素
2.通過增強的for循環刪除符合條件的一個元素
3.通過普通的for刪除刪除符合條件的多個元素
4.通過Iterator進行遍歷刪除符合條件的多個元素
?
- /**??
- ?*?使用增強的for循環??
- ?*?在循環過程中從List中刪除非基本數據類型以后,繼續循環List時會報ConcurrentModificationException??
- ?*/????
- public?void?listRemove()?{????
- ????List<Student>?students?=?this.getStudents();????
- ????for?(Student?stu?:?students)?{????
- ????????if?(stu.getId()?==?2)?????
- ????????????students.remove(stu);????
- ????}????
- }????
- /**??
- ?*?像這種使用增強的for循環對List進行遍歷刪除,但刪除之后馬上就跳出的也不會出現異常??
- ?*/????
- public?void?listRemoveBreak()?{????
- ????List<Student>?students?=?this.getStudents();????
- ????for?(Student?stu?:?students)?{????
- ????????if?(stu.getId()?==?2)?{????
- ????????????students.remove(stu);????
- ????????????break;????
- ????????}????
- ????}????
- }????
- /**??
- ?*?這種不使用增強的for循環的也可以正常刪除和遍歷,??
- ?*?這里所謂的正常是指它不會報異常,但是刪除后得到的??
- ?*?數據不一定是正確的,這主要是因為刪除元素后,被刪除元素后??
- ?*?的元素索引發生了變化。假設被遍歷list中共有10個元素,當??
- ?*?刪除了第3個元素后,第4個元素就變成了第3個元素了,第5個就變成??
- ?*?了第4個了,但是程序下一步循環到的索引是第4個,??
- ?*?這時候取到的就是原本的第5個元素了。??
- ?*/????
- 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);????
- ????????}????
- ????}????
- }????
?
- /**??
- ?*?使用Iterator的方式可以順利刪除和遍歷??
- ?*/????
- 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();//這里要使用Iterator的remove方法移除當前對象,如果使用List的remove方法,則同樣會出現ConcurrentModificationException????
- ????}????
- ????System.out.println(students);????
- }???