Java --- Iterator 迭代器使用详细介绍

    Iterator对象称为迭代器(设计模式的一种),主要用于遍历Collection集合的元素。GOF给迭代器定义:提供一种方法访问一个容器对象中各个元素,而又不暴露该对象的内部细节。

Collection接口继承了java.lang.Iterator接口:

public interface Collection<E> extends Iterable<E> {...}
public interface Iterable<T> {...}

该接口有一个iterator()方法,所有实现Collection接口的集合类都有一个iterator()方法:

Iterator<E> iterator();

用于返回一个实现Iterator接口的对象。

一,下面,小编我来演示一下迭代器的使用:

public class TestNew {

    public static void main(String[] args) {
    	//1,声明一个集合
		Collection collection =  new ArrayList<>();
		//2,在集合中加入数据
        collection.add("a");
        collection.add("b");
        collection.add("c");
        collection.add("d");
        collection.add(12);
        //3,创建迭代器
        Iterator iterator = collection.iterator();
        //4,使用迭代器遍历集合
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //5,方法介绍:hasNext()是判断下一位置是否有值。
        //next()是获取下一位置的值
	}
}

输出:

D:\jdk\jdk1.8.0_171\bin\java.exe
a
b
c
d
12

二,另外,迭代器还有 remove() 方法经常使用,作用是:删除集合中的元素。

Iterator iterator = collection.iterator();
while (iterator.hasNext()){
            if ("a".equals(iterator.next())){
                iterator.remove();
            }
        }
iterator =   collection.iterator(); //此处需要重新声明,不然会执行报错
while (iterator.hasNext()){
    System.out.println(iterator.next());
}

输出:

D:\jdk\jdk1.8.0_171\bin\java.exe
b
c
d
12

三,迭代器错误使用演示:

错误方式1:java.util.NoSuchElementException

Iterator iterator = collection.iterator();
while (iterator.next() != null){
            System.out.println(iterator.next());
        }

错误方式2:一直打印第一个值

Iterator iterator = collection.iterator();
while (collection.iterator().hasNext()){
            System.out.println(collection.iterator().next());
        }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皮皮克克

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值