Java--Iterator迭代器

一个人想着一个人 提交于 2020-01-24 21:50:53

Iterator迭代器

使用Iterator接口遍历集合元素

  • Iterator对象成为迭代器(设计模式的一种)主要用于遍历Collection集合的元素。
  • Iterator仅用于遍历集合
  • 集合对象每次调用iterator()方法都得到一个全新的迭代对象

集合元素的遍历操作,使用迭代器Iterator()接口:

  • 1,内部的方法:hasNext()和next()
  • 2,集合对象每次调用iterator()方法都得到一个全新的迭代器对象
  • 默认游标都在集合的第一个元素之前
    @Test
    public void test1(){
        Collection coll=new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom",20));

        Iterator iterator=coll.iterator();


//        方法一:不推荐
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//
//        方法二:不推荐
//        for(int i=0;i<coll.size();i++) {
//            System.out.println(iterator.next());
//        }
//
        //方法三:推荐
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

        System.out.println(coll);
    }

remove()方法:

  @Test
    public void test2(){
        Collection coll=new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom",20));

        Iterator iterator=coll.iterator();

        //如果还未调用next()或在上一次调用next()方法之后已经调用remove()方法
        //再次调用remove()都会报IlleagalStateException.
        while(iterator.hasNext()){
            Object obj=iterator.next();
            if("456".equals(obj)){
                iterator.remove();
            }
        }

        iterator=coll.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }

在next()之前,指针在集合的上方(头个元素的上面),next()时,指针下移,返回指针指向的元素。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!