0
点赞
收藏
分享

微信扫一扫

Java迭代器-Iterator

认真的老去 2021-12-29 阅读 108

单一职责原则

所有的集合的基本接口是Collection接口。它包含两个方法 (值得一提的是,Collection接口扩展了Iterable接口,因此实现Collection接口,也必须同时实现Iterable接口,从关系上来看,Collection接口是依赖于Iterable的)

Collection接口的方法

Iterable接口的方法

这里需要注意的是,它提供了一个Iterator方法,返回了一个实现了Iterator接口的对象。那么这个Iterator接口又提供了什么方法呢?分别是hashNext()、next()、remove()、forEachRemaining(Consumer<? super E> action)

Iterator接口


这个Iterator,就是所谓的迭代器了。

如何使用迭代器遍历集合中的元素
  • 使用传统的hasNext()&next()
        Collection<String> c = new HashSet<>();
        c.add("a");
        c.add("b");
        Iterator<String> iterator = c.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

那么有没有更加好的遍历集合的办法呢?有,使用foreach.
forEachRemaining具体的访问顺序取决于你使用的集合类型,ArrayList是有序的,HashSet则不保证顺序.

        Collection<String> c = new HashSet<>();
        c.add("a");
        c.add("b");
        //foreach
        for (String element : c) {
            System.out.println(element);
        }
        //lambda
        c.forEach(element -> System.out.println(element));
此时插播一个问题:List如何在遍历中删除元素
  • 使用迭代器遍历,并且使用remove()方法
  • 使用for循环,每次remove的时候,记得让索引-1
  • 使用Java8提供的removeIf()(推荐)
错误示范:

正确示范:
        Collection<String> c = new HashSet<>();
        c.add("a");
        c.add("b");
        c.removeIf(e-> e.equals("a"));
        c.forEach(element -> System.out.println(element));
关于remove方法的一些说明

remove方法将会删除上次调用next方法时返回的元素。当你使用remove方法的时候,需要先获取到有意义的元素(即调用next方法)。在Java核心技术卷这本书中,强调了next方法与remove方法必须具备依赖性。

错误示范
        Collection<String> c = new HashSet<>();
        c.add("a");
        c.add("b");
        Iterator<String> iterator = c.iterator();
        iterator.remove();
正确示范
        Collection<String> c = new HashSet<>();
        c.add("a");
        c.add("b");
        Iterator<String> iterator = c.iterator();
        iterator.next();
        iterator.remove();
迭代器在集合中的作用

用于编写泛型接口,无需为同一个逻辑编写多个方法。

举报

相关推荐

0 条评论