关于Iterator的remove()方法

来源:互联网 发布:linux查看文件命令大小 编辑:程序博客网 时间:2024/05/24 01:47

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

0 0
原创粉丝点击