前言
相比于C++容器遍历删除元素(链接),Java语言遍历删除集合元素在写法上略有差异。
正文
对于Java语言,推荐使用迭代器的删除方法在遍历的过程中删除元素,以List为例示例如下:
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();//使用迭代器的删除方法删除}}
注意,不能将上述例子中的iterator.remove(); 改为list.remove(student); 这将导致ConcurrentModificationException异常。
在Java8之后,推荐使用removeIf进行删除。
