Iterator.remove()是删除最近(最后)使用next()方法的元素。
从迭代器指向的集合中移除迭代器返回的最后一个元素(可选操作)。每次调用 next 只能调用一次此方法。
import java.util.*;
public class test {
public test() {
}
public static void main(String[] args) {
test test1 = new test();
java.util.Collection c=null;
java.util.ArrayList al=new java.util.ArrayList();
for(int i=0;i<10;i++){
String str=i+"";
al.add(str);
}
c=al;
java.util.Iterator it=c.iterator();
for(int i=0;i<3;i++){
System.out.println((String)it.next());
}
it.remove();
it=c.iterator(); //关键的!!!
while(it.hasNext()){
System.out.println((String)it.next());
}
}
}
结果是:
0
1
2
0
1
3
4
5
6
7
8
9
---------------------------------------------------------------------------------------
import java.util.*;
public class Test {
public static void main(String[] args) {
// TODO: Add your code here
Vector v = new Vector();
System.out.println("please enter number");
int b = 0;
while (true) {
try {
b = System.in.read();
} catch (Exception e) {
}
if (b == '\n' || b == '\r')
break;
else {
int num = b - '0';
v.addElement(new Integer(num));
}
}
int sum = 0;
Iterator iterator= v.iterator();
for (int i = 0; i < 3; i++) {
System.out.println((Integer) iterator.next());
}
iterator.remove();
iterator = v.iterator();
while (iterator.hasNext()) {
Integer intobj = (Integer)iterator.next();
sum += intobj.intValue();
System.out.print(intobj);
}
System.out.println();
System.out.println(sum);
}
}