Java迭代器Iterator的remove()方法

遍历Java集合(Arraylist,HashSet...)的元素时,可以采用Iterator迭代器来操作

Iterator接口有三个函数,分别是hasNext(),next(),remove()。

今天浅谈remove函数的作用

官方解释为:

Removes from the underlying collection the last element returned by this iterator (optional operation). 
This method can be called only once per call to next().
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

译:从底层集合中移除此迭代器返回的最后一个元素(可选操作)。 每次调用next()时,只能调用此方法一次。 如果在迭代正在进行中以除调用此方法之外的任何方式修改基础集合,则未指定迭代器的行为。

官方说法现在先不研究

举个例子1:在使用迭代器遍历集合的过程中,使用集合对象的remove方法删除数据时,查看迭代器的运行情况。

List<String> all = new ArrayList<String>();
all.add("a");
all.add("b");
all.add("c");
        
Iterator<String> iterator=all.iterator();//实例化迭代器
while(iterator.hasNext()){
    String str=iterator.next();//读取当前集合数据元素
    if("b".equals(str)){
        all.remove(str);
    }else{
        System.out.println( str+" ");
    }
}
System.out.println("
删除"b"之后的集合当中的数据为:"+all);

输出结果为:

发现:使用集合对象 all 的 remove() 方法后,迭代器的结构被破坏了,遍历停止了

---------------------------------------------------------------------------------------------------

举个例子2:在使用迭代器遍历集合的过程中,使用迭代器的 remove 方法删除数据时,查看迭代器的运行情况

List<String> all = new ArrayList<String>();
all.add("a");
all.add("b");
all.add("c");
        
Iterator<String> iterator = all.iterator();//实例化迭代器
        
while(iterator.hasNext()){
    String str=iterator.next();//读取当前集合数据元素
    if("b".equals(str)){
        //all.remove(str);//使用集合当中的remove方法对当前迭代器当中的数据元素值进行删除操作(注:此操作将会破坏整个迭代器结构)使得迭代器在接下来将不会起作用
        iterator.remove();
    }else{
        System.out.println( str+" ");
    }
}
System.out.println("
删除"b"之后的集合当中的数据为:"+all);

运行结果

 发现:使用迭代器 的 remove() 方法后,迭代器删除了当前读取的元素 “b”,并且继续往下遍历元素,达到了在删除元素时不破坏遍历的目的

原文链接:https://blog.csdn.net/qq_30310607/article/details/82347807

原文地址:https://www.cnblogs.com/cy0628/p/15384585.html