zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Codeforces 362D Fools and Foolproof Roads 构造题
    Machine Learning—Mixtures of Gaussians and the EM algorithm
    Php面向对象 – 单例模式
    标C编程笔记day06 动态分配内存、函数指针、可变长度參数
    html的下拉框的几个基本使用方法
    【创新培育项目】为什么要组队參加比赛?及如何寻找一个合适的选题?
    项目管理心得:一个项目经理的个人体会、经验总结
    GMM的EM算法实现
    oracle中LAG()和LEAD()等分析统计函数的使用方法(统计月增长率)
    sql server 2005 32位+64位、企业版+标准版、CD+DVD 下载地址大全
  • 原文地址:https://www.cnblogs.com/cy0628/p/15384585.html
Copyright © 2011-2022 走看看