我正在浏览 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]
最佳答案
If I use both the while loops the iterator does not remove the element from the list, why?
因为当第一个循环完成时,迭代器的 hasNext
为 false。因此代码根本不会进入第二个循环。
要第二次循环,您必须获得一个新的迭代器。
在支持它的集合中,您可以使用remove
在一个循环中打印和删除。迭代器的方法。
while(itr.hasNext()){
String remo=(String)itr.next();
System.out.print(" " +remo+" ");
if(remo.equals(removeE)){
itr.remove();
}
}
关于java - 如何同时打印和删除迭代器中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17884828/