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());
}
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());
}
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
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();
}
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
1
2
3
4
5
6
7
8
9
remove()后,对下面的元素遍历没影响 .完毕