文章目录
Iterator介绍
替代Enumeration遍历集合,相比Enumeration,Iterator接口提供了删除方法。1.8以后新增方法forEachRemaining(Consumer<? super E> action),遍历剩余所有元素,并将参数action作用到每个元素。
接口方法
声明方法 | 描述 |
---|---|
boolean hasNext() | 判读是否还存在元素 |
E next() | 返回下一个元素的值,如果没有抛出异常 |
default void remove() | 默认抛出异常,根据需要重写:删除当前遍历最后一个元素 ,在调用next()之后操作 |
default void forEachRemaining(Consumer<? super E> action) | 默认根据action遍历所有剩余元素 |
示例
描述:着重练习 remove 和 forEachRemaining方法
- 创建Iterator实现类
- 在Main函数中分别调用remove和forEachRemaining方法
自定义类
package practice.collection.zzj;
import java.util.*;
/**
* 老师名称迭代器
*/
public class TearchIterator implements Iterator<String> {
// 老师名称列表
private List<String> tearchNames = new ArrayList<>(Arrays.asList("数学","语文","英语","物理"));
// 当前索引
int currentIndex = 0;
// 元素总数
int totalCount =tearchNames.size();
// 是否已经删除
boolean hasRemove = false;
/**
* 判断是还有元素
* @return
*/
@Override
public boolean hasNext() {
if(currentIndex<totalCount){
return true;
}
return false;
}
/**
*返回当前元素
* @return
*/
@Override
public String next() {
hasRemove = false;
if(currentIndex<totalCount){
return tearchNames.get(currentIndex++);
}else{
throw new NoSuchElementException("empty");
}
}
@Override
public void remove() {
if(!hasRemove){
hasRemove = true;
if(currentIndex>0){
tearchNames.remove(currentIndex-1);
totalCount--;
}else{
throw new IllegalStateException("还没有调用next");
}
}else{
throw new IllegalStateException("已经调用过");
}
}
public String toString(){
return "["+String.join(",",tearchNames)+"]";
}
}
启动类
import practice.collection.zzj.TearchIterator;
public class Main {
public static void main(String[] args){
testRemove();
System.out.println("*******************************************************");
testForRemaining();
}
/**
* 删除测试
*/
private static void testRemove(){
TearchIterator tearchIterator = new TearchIterator();
while(tearchIterator.hasNext()){
String name = tearchIterator.next();
if(name.equals("英语")){
// 删除英语老师
tearchIterator.remove();
}
}
System.out.println(tearchIterator);
}
/**
* forEachRemaining测试
*/
private static void testForRemaining(){
TearchIterator tearchIterator = new TearchIterator();
// 打印所有老师名称
tearchIterator.forEachRemaining(m->System.out.print(","+m));
}
}
结果
[数学,语文,物理]
*******************************************************
,数学,语文,英语,物理
Process finished with exit code 0
如果需要遍历操作 引用类型,forEachRemaining还是很方便的