当前位置:  首页>> 技术小册>> Java语言基础10-Java中的集合

Iterator 接口中有一个删除的方法:

  1. default void remove() {
  2. throw new UnsupportedOperationException("remove");
  3. }
  • 既然,Collection 接口中已经有了 remove(xxx) 的方法,为什么 Iterator 迭代器中还要提供 remove() 方法?
  • 因为Collection 接口的 remove(xxx) 方法无法根据指定条件删除。

注意:不要在使用 Iterator 迭代器迭代元素的时候,调用 Collection 的 remove(xxx) 方法,否则会报 java.util.ConcurrentModificationException 异常或出现其他不确定的行为。

  • 示例:删除集合中的偶数元素
  1. package com.github.collection1.demo3;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.Iterator;
  5. /**
  6. * @author maxiaoke.com
  7. * @version 1.0
  8. */
  9. public class Test {
  10. public static void main(String[] args) {
  11. Collection<Integer> collection = new ArrayList<>();
  12. collection.add(1);
  13. collection.add(2);
  14. collection.add(3);
  15. collection.add(4);
  16. System.out.println("原来集合中的元素 = " + collection); // 原来集合中的元素 = [1, 2, 3, 4]
  17. for (Iterator<Integer> iterator = collection.iterator(); iterator.hasNext();) {
  18. Integer ele = iterator.next();
  19. if (ele % 2 == 0) {
  20. iterator.remove();
  21. }
  22. }
  23. System.out.println("后来集合中的元素 = " + collection); // 后来集合中的元素 = [1, 3]
  24. }
  25. }