2013-07-26 34 views
0

我正在瀏覽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] 

回答

4

如果我同時使用,而循環,循環不從列表中,爲什麼刪除元素?

因爲當第一個循環完成時,迭代器的hasNext爲false。所以代碼永遠不會進入第二個循環。

要循環第二次,你必須得到一個新的迭代器。

在支持它的集合中,您可以通過使用迭代器的remove方法在一個循環中進行打印和刪除。

while(itr.hasNext()){ 
    String remo=(String)itr.next(); 
    System.out.print(" " +remo+" "); 
    if(remo.equals(removeE)){ 
     itr.remove(); 
    } 
} 
0

你正在做的:

while(itr.hasNext()){ 
    System.out.print(" " +itr.next()+" "); 
} 
while(itr.hasNext()){ 

所以第一後while循環你的迭代器將完成。

相關問題