首页 > 其他分享 >迭代器Iterator

迭代器Iterator

时间:2022-09-30 16:15:27浏览次数:49  
标签:Iterator 迭代 lastRet elementData public new ArrayList

  学集合之前我们先来学习迭代器?那什么是迭代器。

  迭代器是对集合进行遍历,而每一个集合内部的存储结构都是不同的,所以每一个集合存和取都是不一样,那么就需要在每一个类中定义hasNext()和next()方法,这样做是可以的,但是会让整个集合体系过于臃肿,迭代器是将这样的方法向上抽取出接口,然后在每个类的内部,定义自己迭代方式,这样做的好处有二,第一规定了整个集合体系的遍历方式都是hasNext()和next()方法,迭代器对象在遍历集合时,内部采用指针的方式来跟踪集合中的元素

  以ArrayList中内部类itr实现的迭代器为例。

源码:

   public boolean hasNext() {
      return cursor != size;
  }

  @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;//获取当前元素索引
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;//获取数组对象
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;//索引前进
            return (E) elementData[lastRet = i];//将当前索引赋给上一个lastRet标记
        }

 

   public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();//检查是不是预期的modCount和原本的modCount相等,防止在迭代的时候对元素进行操作
            try {
                ArrayList.this.remove(lastRet);//调用集合的remove方法
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
 

 

  @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);//调用子类实现的accept方法对当前元素进行操作
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

 

测试forEachRemaining例子

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

public class THS {

    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        Iterator<Integer> iterator = arrayList.iterator();
        while (iterator.hasNext()){
            int c = iterator.next();
            System.out.println(c);
        }
        Iterator<Integer> iterator1 = arrayList.iterator();
        if (iterator1.hasNext()){
            System.out.println(iterator1.next()+"测试");
        }
        while (iterator1.hasNext()){
           iterator1.forEachRemaining(e -> System.out.println(e+"测试"));
        }
    }
}

 

 

标签:Iterator,迭代,lastRet,elementData,public,new,ArrayList
From: https://www.cnblogs.com/thh19201420/p/16745174.html

相关文章

  • 迭代器模式 Iterator
    “数据结构”模式常常有一些组件在内部具有特定的数据结构,如果让客户程序依赖这些特定的数据结构,将极大地破坏组件的复用。这时候,将这些特定数据结构封装在内部,在外部提......
  • 迭代器iterator在程序到底起什么作用? ——整理
    1.类似于一个指针,但不是指针2.在container中相当于指向element的指针,但其实现并不是指针,而是对象。 3.从大的方面讲是容器和算法之间的黏合剂从小的方面讲是类似智能指针......
  • Python基础(八) | 深浅拷贝、生成器、迭代器以及装饰器详解
    ⭐本专栏旨在对Python的基础语法进行详解,精炼地总结语法中的重点,详解难点,面向零基础及入门的学习者,通过专栏的学习可以熟练掌握python编程,同时为后续的数据分析,机器学习及深......
  • ES6--》了解并应用迭代器与生成器
    迭代器迭代器(Iterator)也叫遍历器,是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作;JS中原有表示“集合”的数据......
  • [数值分析]牛顿迭代法Newton!!!
    牛顿迭代法Newton!!!牛顿迭代法的基本思想牛顿迭代法是一种用来求解方程的方法,它的基本思想是:如果一个函数在某一点的切线是直线,那么迭代下一次产生的值就是切线与x轴的......
  • 迭代器遍历对象 快速失败和安全失败
    一、快速失败(fail—fast)在用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了修改(增加、删除、修改),则会抛出ConcurrentModificationException。原理:迭......
  • Java: Iterator/Cursor Patterns
    /***版权所有2022涂聚文有限公司*许可信息查看:*描述:*迭代器模式Iterator/CursorPatterns*历史版本:JDK14.02*2022-09-12创建者geovindu*2022......
  • Python 异步迭代器
    1、参考来源https://docs.python.org/zh-cn/3.9/reference/datamodel.html?highlight=aiter#asynchronous-iterators2、代码示例:1#-*-coding:utf-8-*-2"""......
  • 算法竞赛进阶指南 0x24 迭代加深
    对于深度优先,如果答案在很浅的部位,但是整个搜索树过于深,那么就会寄掉。但是对于广度优先,本来挺好,但是在队列里面存储太多的元素,到时爆。同时,广度优先也不容易存储数据。......
  • 实例85 牛顿迭代法求解方程
    #include<stdio.h>#include<math.h>#include<stdlib.h>intFunction(double,double*,double*);intNewton(double*,double,int);intFunction(x,f,dy)dou......