https://blog.csdn.net/github_2011/article/details/54927531
這是List接口中的方法,List集合調用此方法可以得到一個迭代器對象(Iterator)。
for example:
- //准備數據
- List<Student> list = new ArrayList<>();
- list.add(new Student("male"));
- list.add(new Student("female"));
- list.add(new Student("female"));
- list.add(new Student("male"));
- //遍歷刪除,除去男生
- Iterator<Student> iterator = list.iterator();
- while (iterator.hasNext()) {
- Student student = iterator.next();
- if ("male".equals(student.getGender())) {
- iterator.remove();//使用迭代器的刪除方法刪除
- }
- }
這種使用迭代器遍歷、並且使用迭代器的刪除方法(remove()) 刪除是正確可行的,也是開發中推薦使用的。
誤區:
如果將上例中的iterator.remove(); 改為list.remove(student);將會報ConcurrentModificationException異常。
這是因為:使用迭代器遍歷,卻使用集合的方法刪除元素的結果。
https://blog.csdn.net/github_2011/article/details/54927531