当前位置:网站首页>什么是迭代器
什么是迭代器
2022-04-21 07:16:00 【_.JUN】
迭代器!
what(是什么)
迭代器是一种(遍历集合元素的)模式
function
是用来遍历集合内部元素
why 为什么会有迭代器这个东西
因为像有序的集合里边,可以直接通过for循环的方式get(index)遍历得到每一个元素, 而如果是无序集合,则不能通过get(index)得到集合里边的元素,迭代器就应运而生,尽管可以通过增强for循环也能对无序的集合进行遍历,但其内部亦是采用迭代器实现。
迭代器优势
迭代器提供一种对容器对象中的各个元素进行访问的方法,而又不需暴露该对象的内部细节。迭代器是一种模式,它可以使得对于序列类型的数据结构的遍历行为与被遍历的对象分离,即我们无需关心该序列的底层结构是什么样子的。只要拿到这个对象,使用迭代器就可以遍历这个对象的内部.
how (怎么使用迭代器)
需要遍历的集合调用iterator()方法,返回一个迭代器对象,hashNext()方法判断这个集合里边是否还有未遍历完的元素,直到集合没有元素可遍历循环结束则结束
迭代器遍历写法:
while写法
package come.XieZhiJun.Daily._April4_18;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class IteratorTest {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(111);
list.add(222);
list.add(333);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
int value = iterator.next();
System.out.print(value + " ");
}
}
}
运行结果

for写法
package come.XieZhiJun.Daily._April4_18;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class IteratorTest {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(111);
list.add(222);
list.add(333);
for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext(); ) {
Integer next = iterator.next();
System.out.println(next);
}
}
}
运行结果也是一样的

版权声明
本文为[_.JUN]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_65358120/article/details/124264160
边栏推荐
- Install the go plug-in in vscode and configure the go environment to run go
- Package and download files
- Build openwrt file system for i.mx6q development board
- go语言中的读写锁以及协程通信
- 迅为STM32MP157开发板编译U-Boot
- It can be downloaded to the data set running loam
- Apache solr 远程代码执行漏洞(CVE-2019-0193)复现
- 【项目】小帽外卖(五)
- Technical background and practical role of "industrial digitization"
- Apache-Skywalking-SQL注入(CVE-2020-9483)复现
猜你喜欢
随机推荐
J'ai accidentellement trouvé la base de données d'une soeur Tsinghua!
Virtual machine host Ping SSH campus network bridge net
Nail custom robot docking source code
Restful规范和使用
sys.stdin.readline和readlines以及input()
树的基本概念与存储结构
Picture material free material picture material website picture material where to find some picture material download the purpose of picture material picture material product picture material website
2022 examination question bank and simulation examination of special operation certificate for hoisting machinery command
C a complete class that generates Chinese amount and reads it out by voice
BurpSuite工具详解及暴库示例
HTTP缓存策略与方案
Vim插件管理插件Vim-plug
数据库实验一、数据库的创建及基本查询
【以太网交换安全】--- 端口隔离运行原理及二层隔离三层通信实例配置讲解
openfeign调用时传递文件
NAS选购参考对比
Unity---枚举类
PDF OCR
PHP Chinese to English initials
Project storage log








