Java迭代器Iterator代码详解(迭代器模式)

你好我是辰兮,很高兴你能来阅读,本篇给你介绍Java设计模式之迭代器模式,简单的讲解Iterator具体如何使用,分享给初学者,大家一起进步!



一、迭代器介绍

迭代器模式介绍

所谓迭代器模式就是提供一种方法顺序访问一个聚合对象中的各个元素,而不是暴露其内部的表示。迭代器模式是将迭代元素的责任交给迭代器,而不是聚合对象,我们甚至在不需要知道该聚合对象的内部结构就可以实现该聚合对象的迭代。

在这里插入图片描述

通过迭代器模式,使得聚合对象的结构更加简单,它不需要关注它元素的遍历,只需要专注它应该专注的事情,这样就更加符合单一职责原则了。

来来来仔细一起简单看看它有哪些方法!

public interface Iterator<E> {
    
    
    boolean hasNext();//判断是否存在下一个对象元素

    E next();//获取下一个元素

    void remove();//移除元素
}

在这里插入图片描述
迭代器模式:一种遍历访问聚合对象中各个元素的方法,不暴露该对象的内部结构。


二、ArrayList案例

首先我们创建一个集合,然后先后使用迭代器;for循环;foreach来看看打印出来效果;

public class IteratorTest {
    
    
    
    public static void main(String[] args) {
    
    
        ArrayList arrayList = new ArrayList();
        arrayList.add("你好我是辰兮");
        arrayList.add("很高兴你能来阅读");
        arrayList.add(2020);
        arrayList.add("一起进步");
        Iterator iterable = arrayList.iterator();
        //配合while()循环实现遍历输出
        while (iterable.hasNext()){
    
    
            System.out.println("while循环出来的数据是:"+iterable.next());
        }
        //while()中的判断条件it.hasNext()用于判断it中是否还有下一元素,有的话就继续循环,输出语句中的it.next()既可以使“指针”往后走一位,又能将当前的元素返回,用于输出。
        System.out.println("======================================");
        //配合for()循环实现遍历输出:
         for(Iterator it = arrayList.iterator(); it.hasNext();){
    
    
             System.out.println("for循环出来的数据是:"+it.next());
             //可以自己调用移除方法测试
             //it.remove();
            }
        System.out.println("======================================");

         //foreach 循环来代替Iterator
        for (Object a:arrayList) {
    
    
            System.out.println("foreach出来的数据是:"+a);
        }
         //for each 不适合用来增删元素,如果单纯用来遍历元素,这种写法也许会更简洁一点。
    }
}

运行结果

扫描二维码关注公众号,回复: 12015239 查看本文章
while循环出来的数据是:你好我是辰兮
while循环出来的数据是:很高兴你能来阅读
while循环出来的数据是:2020
while循环出来的数据是:一起进步
======================================
for循环出来的数据是:你好我是辰兮
for循环出来的数据是:很高兴你能来阅读
for循环出来的数据是:2020
for循环出来的数据是:一起进步
======================================
foreach出来的数据是:你好我是辰兮
foreach出来的数据是:很高兴你能来阅读
foreach出来的数据是:2020
foreach出来的数据是:一起进步

Process finished with exit code 0

这里备注一下再foreach中你使用removeIDEA也会自带提示,foreach不适合用了增删元素

在这里插入图片描述

迭代器方法源码:当迭代器对象调用iterator()的时候返回的是Iterator本身

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     *
     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public Iterator<E> iterator() {
    
    
        return new Itr();
    }

第一次学习迭代器的时候总觉得这个单词和这个语法不好记忆,很别扭,如果不好理解就看看源码,就知道为什么了


三、HashMap案例

我们对比创建一个HashMap的对象,然后先后使用迭代器;for循环;foreach来看看打印出来效果;

public class IteratorMapTest {
    
    

    public static void main(String[] args) {
    
    
        HashMap<String,String> map = new HashMap<>();
        map.put("1","hello");
        map.put("2","辰兮");
        map.put("3","一起进步");
        map.put("4","fighting");
        Iterator<Map.Entry<String, String>> iterable = map.entrySet().iterator();
        //while循环测试
        while (iterable.hasNext()){
    
    
            System.out.println("while循环中测试:"+iterable.next());
        }
        System.out.println("=============================");
        //for循环测试
        for (  Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();it.hasNext();){
    
    
            System.out.println("for循环测试"+it.next());
        }
        System.out.println("=============================");
        //Map接口下的iterator应用方法与Collection中的略微有些不同,用到了entrySet()方法,entrySet()用来返回整个键—值对。
        //foreach测试数据
        for (Object object:map.entrySet()) {
    
    
            System.out.println("foreach测试数据:"+object);
        }
    }
}

运行结果

while循环中测试:1=hello
while循环中测试:2=辰兮
while循环中测试:3=一起进步
while循环中测试:4=fighting
=============================
for循环测试1=hello
for循环测试2=辰兮
for循环测试3=一起进步
for循环测试4=fighting
=============================
foreach测试数据:1=hello
foreach测试数据:2=辰兮
foreach测试数据:3=一起进步
foreach测试数据:4=fighting

Process finished with exit code 0

四、拓展相关

Iterator遍历时不可以删除集合中的元素问题

在使用Iterator的时候禁止对所遍历的容器进行改变其大小结构的操作。例如: 在使用Iterator进行迭代时,如果对集合进行了add、remove操作就会出现ConcurrentModificationException异常。

案例

public class Test {
    
    
    public static void main(String[] args)  {
    
    
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
    
    
            System.out.println(iterator.next());
            list.remove(iterator.next());
        }
    }
}

运行结果

1
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
	at java.util.ArrayList$Itr.next(ArrayList.java:851)
	at com.example.rabbitmq.test.Test.main(Test.java:21)

Process finished with exit code 1

The best investment is to invest in yourself.

在这里插入图片描述

2020.09.26 愿你们奔赴在自己的热爱里!

猜你喜欢

转载自blog.csdn.net/weixin_45393094/article/details/108809562
今日推荐