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);
}

相关内容

热门资讯

2月末我国外储规模3.4万亿美... 21世纪经济报道记者 边万莉 3月7日,国家外汇管理局公布2026年2月末外汇储备规模数据。截至20...
谷歌NotebookLM新增功...   炒股就看金麒麟分析师研报,权威,专业,及时,全面,助您挖掘潜力主题机会! (来源:IT之家)I...
国际原油价格飙升!下周调价窗口... 受中东地缘冲突持续等影响,国际原油价格再度飙升,WTI原油、布伦特原油价格已双双站上90美元/桶,创...
假装“出走”   ▌星闪  开学快一礼拜了,暖爸才告诉我,寒假里小暖的离家出走是他帮着策划的。  女儿小暖读初二了...
教育部部长答人民日报社《民生周... 今天上午,十四届全国人大四次会议在梅地亚中心新闻发布厅举行民生主题记者会,教育部部长怀进鹏、民政部部...