[英]How to print and remove elements in iterator simultaneously?
I was going through collections in Java and came across some iterator examples. 我正在浏览Java中的集合,并遇到了一些迭代器示例。 I am giving the code below
我在下面的代码
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]
Why? 为什么?
If I use both the while loops the iterator does not remove the element from the list, why? 如果我同时使用while循环,则迭代器不会从列表中删除元素,为什么? Can you help me out.
你能帮我吗。
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 gives output 上面的代码给出了输出
[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?
如果我同时使用while循环,则迭代器不会从列表中删除元素,为什么?
Because when the first loop is complete, the iterator's hasNext
is false. 因为当第一个循环完成时,迭代器的
hasNext
为false。 So the code never enters the second loop at all. 因此,代码根本不会进入第二个循环。
To loop a second time, you'd have to get a new iterator. 要第二次循环,您必须获得一个新的迭代器。
In collections that support it, you could both print and remove in one loop by using the remove
method of the iterator. 在支持它的集合中,您可以使用迭代器的
remove
方法在一个循环中进行打印和删除。
while(itr.hasNext()){
String remo=(String)itr.next();
System.out.print(" " +remo+" ");
if(remo.equals(removeE)){
itr.remove();
}
}
You are doing: 您正在执行:
while(itr.hasNext()){
System.out.print(" " +itr.next()+" ");
}
while(itr.hasNext()){
so after first while loop your iterator will be completed. 因此,在第一次while循环之后,您的迭代器将完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.