关于Iterator的remove()方法

本文通过示例代码详细解析了Java中Iterator的remove()方法的功能及使用方式,验证了该方法仅移除当前迭代器指向的元素,并不影响后续元素的遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    今天看到,java的NIO里面的SelectionKey,处理完key后,调用keyIterator.remove();   对Iterator的remove()方法不是很熟悉,小测试了下,代码如下: 
        List<String> list = new ArrayList<String>();
        
for (int i = 0; i < 10; i++) {
            String str 
= i + "";
            list.add(str);
        }
        java.util.Iterator it 
= list.iterator();
        
for (int i = 0; i < 5; i++) {
            System.out.println((String) it.next());
        }
        it.remove();
        System.out.println("////////////////////////");
        it 
= list.iterator();
        
while (it.hasNext()) {
            System.out.println((String) it.next());
        }

运行结果如下:

0
1
2
3
4
////////////////////////
0
1
2
3
5
6
7
8
9

  很明显,remove()去掉的是当前it.next()返回的元素.到这里有个疑问,这个remove之后对下面的元素遍历有没有影响呢?又测试下,代码如下:

     List<String> list = new ArrayList<String>();
        
for (int i = 0; i < 10; i++) {
            String str 
= i + "";
            list.add(str);
        }
        java.util.Iterator it 
= list.iterator();
//        for (int i = 0; i < 5; i++) {
//            System.out.println((String) it.next());
//        }
//        it.remove();
//        System.out.println("////////////////////////");
//        it = list.iterator();
//        while (it.hasNext()) {
//            System.out.println((String) it.next());
//
//        }
        while (it.hasNext()) {
            System.out.println((String) it.next());
            it.remove();
        }

运行代码如下:

0
1
2
3
4
5
6
7
8
9

 

remove()后,对下面的元素遍历没影响 .完毕!

转载于:https://www.cnblogs.com/ethanchan/archive/2010/02/23/1672235.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值