【Java笔记(35)】Iterator接口与iterator()方法在1.5前后的区别。

一、核心要点

1、接口结构

在这里插入图片描述

2、注意事项

1、在迭代中主要用到的是Iterator迭代
2、在迭代时,使用hasNext()next()获取元素
3、在迭代中删除元素,要使用Iterator接口中都remove(),如果使用Collection接口中
	的remove()会抛出异常。java.util.ConcurrentModificationException,并发修改。
4、Set和List对象通过iterator()方法获取Iterator对象,这个方法在1.5之前是在
	Collection接口中,在1.5之后是在Iterable接口中。

二、完整代码

package collectjh.iterator;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Iterator迭代输出
 *
 * @ClassName: IteratorDome
 * @Author: Xlu
 * @Date: 2020-06-19 9:23
 * @Version 11
 **/
public class IteratorDome {
    public static void main(String[] args) {
        Set<String> all=new HashSet<String>();
        all.add("xlu");
        all.add("103");
        all.add("csdn");

        //1.5之后iterator()方法在Iterable接口里面
        //1.5之前在 Collection接口里面
        Iterator<String> iterator = all.iterator();

        while (iterator.hasNext()) {
            String next = iterator.next();
            if (next.equals("xlu")) {
                //Set和List中的remove()方法都是重写了Collection中的方法
                //如果这里使用Collection中的删除会报错
                //java.util.ConcurrentModificationException
//                all.remove(next);

                //这里则要采用Iterator中的remove方法
                //采用Iterator里面的方法,在原集合之中也会被删除
                //如果没有必要,不使用此方法
                iterator.remove();

            }else{

                System.out.println(next);
            }


        }

    }
}

三、运行结果

103
csdn
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

「已注销」

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

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

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

打赏作者

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

抵扣说明:

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

余额充值