Iterator迭代器
Iterator迭代器
- 提供一种方法访问一个容器(Collection)对象中各个元素,而又不需要暴露该对象的内部细节,迭代器模式,就是为容器而生。
- Collection接口继承了Iterator接口
- 执行原理:1.指针下移。2.将下移以后集合位置上的元素返回
- 顺序遍历、单核时代,现在多核时代不宜使用
常用方法
| 返回类型 |
方法 |
示意 |
| boolean |
hasNext() |
获取迭代器是否有下一个元素 |
| Object |
next() |
从指针0开始下一个元素的值 |
| - |
remove() |
移除当前next指针的元素 |
代码示例
package com.felixfei.study.test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* @author felixfei
* @version 1.0
* @date 2021/3/30 20:40
* @describle 使用迭代器:
*/
public class IteratorTest {
public static void main(String[] args) {
Collection<String> list = new ArrayList<String>();
list.add("b");
list.add("a");
list.add("c");
Iterator<String> iterator = list.iterator();
// 判断是否有下一个元素
while (iterator.hasNext()) {
String next = iterator.next();
if (next.equals("a")) {
// 移除元素
iterator.remove();
}
System.out.println("当前元素的值=" + next);
}
// 移除后需要重新赋值
iterator = list.iterator();
System.out.println("是否有元素" + iterator.hasNext());
while (iterator.hasNext()) {
System.out.println("当前元素的值=" + iterator.next());
}
// 错误遍历方式一 NoSuchElementException
while (iterator.next() != null) {
System.out.println(iterator.next());
}
// 错误遍历方式二 每当调用 iterator()方法都会返回迭代器对象,所以这种方式都会用新对象的next()位置的值
while (list.iterator().hasNext()) {
System.out.println(list.iterator().next());
}
}
}
本文标题:Iterator迭代器
本文链接:https://www.haomeiwen.com/subject/bndohltx.html
网友评论