关于Iterator的remove()方法

Iterator的remove()方法只能删除之前next()方法返回的数据,否则会报错。


  今天看到,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()后,对下面的元素遍历没影响 .完毕

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值