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

迭代器

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

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

两者代码的写法不一样

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

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

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...