java中List遍历删除元素-----不能直接 list.remove()

https://blog.csdn.net/github_2011/article/details/54927531

这是List接口中的方法,List集合调用此方法可以得到一个迭代器对象(Iterator)。

for example:

[java]  view plain  copy
 
  1. //准备数据  
  2.         List<Student> list = new ArrayList<>();  
  3.         list.add(new Student("male"));  
  4.         list.add(new Student("female"));  
  5.         list.add(new Student("female"));  
  6.         list.add(new Student("male"));  
  7.   
  8.         //遍历删除,除去男生  
  9.         Iterator<Student> iterator = list.iterator();  
  10.         while (iterator.hasNext()) {  
  11.             Student student = iterator.next();  
  12.             if ("male".equals(student.getGender())) {  
  13.                 iterator.remove();//使用迭代器的删除方法删除  
  14.             }  
  15.         }  

这种使用迭代器遍历、并且使用迭代器的删除方法(remove()) 删除是正确可行的,也是开发中推荐使用的。

误区:

如果将上例中的iterator.remove(); 改为list.remove(student);将会报ConcurrentModificationException异常。

这是因为:使用迭代器遍历,却使用集合的方法删除元素的结果。

https://blog.csdn.net/github_2011/article/details/54927531

猜你喜欢

转载自www.cnblogs.com/czlovezmt/p/9154604.html