我正在浏览 Java 中的集合,并遇到了一些迭代器示例。我在下面给出代码
public class iteratorexample {
public static void main(String[] args) {
String removeE="New York";
List<String> thelist = new ArrayList<String>();
thelist.add("Dallas");
thelist.add("Richmond");
thelist.add("Atlanta");
thelist.add("New York");
thelist.add("Birmingham");
System.out.print(thelist);
System.out.println();
Iterator<String> itr= thelist.iterator();
/*while(itr.hasNext()){
System.out.print(" " +itr.next()+" ");
} */
**while(itr.hasNext()){
String remo=(String)itr.next();
if(remo.equals(removeE)){
itr.remove();
}
}**
System.out.println();
System.out.println("After removing: ");
System.out.println(thelist);
}
}
Above Code give output
[Dallas, Richmond, Atlanta, New York, Birmingham]
After removing:
[Dallas, Richmond, Atlanta, Birmingham]
为什么?
如果我同时使用 while 循环,迭代器不会从列表中删除元素,为什么?你能帮我吗。
public static void main(String[] args) {
String removeE="New York";
List<String> thelist = new ArrayList<String>();
thelist.add("Dallas");
thelist.add("Richmond");
thelist.add("Atlanta");
thelist.add("New York");
thelist.add("Birmingham");
System.out.print(thelist);
System.out.println();
Iterator<String> itr= thelist.iterator();
while(itr.hasNext()){
System.out.print(" " +itr.next()+" ");
}
while(itr.hasNext()){
String remo=(String)itr.next();
if(remo.equals(removeE)){
itr.remove();
}
}
System.out.println();
System.out.println("After removing: ");
System.out.println(thelist);
}
}
上面的代码给出了输出
[Dallas, Richmond, Atlanta, New York, Birmingham]
Dallas Richmond Atlanta New York Birmingham
After removing:
[Dallas, Richmond, Atlanta, New York, Birmingham]