Iterator 迭代器
创始人
2024-05-30 14:20:59

迭代器

为了兼顾 各个子类的特性
实现无差别可以 访问数据

举个例子
遍历数组和遍历链表
在这里插入图片描述

两者代码的写法不一样

为了实现
使用相同的代码
对不同的数据容器进行遍历
就出现了 迭代器

for语句的执行和 interator的实现息息相关
在这里插入图片描述

目的

访问各个类型 集合 的数据,而不用关心它们的内部实现。
Access the data of various types of collections without caring about their internal implementation.

代码

java中interator是一个接口
主要有两个抽象方法

public interface Interator{boolean hasNext();Object next();
}

hasNext()
用来判断 还有没有数据可以提供访问
next()
用来访问 集合的下一个数据

使用方式

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

集合实现的是 Iterable 接口

public interface Iterable {Iterator iterator();
}

Collection集合 继承 Iterable接口
Collection Collection Inheritance Iterable Interface
因此需要实现相对应的方法
Therefore, corresponding methods need to be implemented

public interface Collection extends Iterable {
}
Collection collection = new ArrayList();
Iterator interator = collection.iterator();
while (iterator.hasNext()) {System.out.println(iterator.next());
}

迭代器具有隔离性和

各个迭代器之间遍历数据互不影响
The traversal data between each iterator does not affect each other

在这里插入图片描述
实现Iterator接口后
可以直接使用for each循环访问
因为其底层用的就是迭代器

Collection collection = new ArrayList();
for (Object o: collection) {System.out.println(o);
}

相关内容

热门资讯

茂硕电源股价跌3.21%,诺安... 5月26日,茂硕电源跌3.21%,截至发稿,报8.14元/股,成交2292.03万元,换手率0.81...
兴全合宜混合A净值上涨0.84... 兴全合宜灵活配置混合型证券投资基金(LOF)(简称:兴全合宜混合A,代码163417)公布5月25日...
天弘文化新兴产业股票A净值上涨... 天弘文化新兴产业股票型证券投资基金(简称:天弘文化新兴产业股票A,代码164205)公布5月25日最...
中信保诚中证500指数(LOF... 中信保诚中证500指数型证券投资基金(LOF)(简称:中信保诚中证500指数(LOF)A,代码165...
中欧行业成长混合(LOF)A净... 中欧行业成长混合型证券投资基金(LOF)(简称:中欧行业成长混合(LOF)A,代码166006)公布...