迭代器的使用

最简单来说就是这样的

import java.util.ArrayList;
import java.util.Iterator;
public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        
        Iterator<Integer> it = arrayList.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}

但是运用时也会出现一些问题比如
1.如果多写了一个.next

while (it.hasNext()) {
           it.next();
           it.next();
 }

就会抛出NoSuchElementException异常,跟数组下标越界差不多吧。
在这里插入图片描述
底层代码如上。
2.迭代器的初始位置是-1也就是所有元素之前,这时候是没办法移除的。抛出IllegalStateException异常

while (it.hasNext()) {
            it.remove();
            it.next();
 }

3.迭代器使用与容器改动交替进行则抛出ConcurrentModificationException异常,原因是因为迭代器所期望的大小与容器本身的大小不同。

Iterator<Integer> it = arrayList.iterator();
        arrayList.remove(0);
        while (it.hasNext()) {
           it.next();
        }

迭代器的remove()方法与容器的remove()方法有什么区别呢?

        while (it.hasNext()) {
            Integer i  = it.next();
           if(i==Integer.valueOf(2)){
               it.remove();
           }else {
               System.out.println(i);
           }
        }
        System.out.println(arrayList);

运行结果如下:
1
3
[1, 3]

while (it.hasNext()) {
            Integer i  = it.next();
           if(i==Integer.valueOf(2)){
               arrayList.remove(i);
           }else {
               System.out.println(i);
           }
        }
        System.out.println(arrayList);

运行结果如下:
1
[1, 3]
原因是对数组的修改破坏了迭代器的结构导致遍历中断。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值