2011-11-07 73 views
3

我在使用Iterator時向我的ArrayList添加元素時遇到問題。在下面的代碼中它給了我這個輸出:在Java中使用Iterator時將元素添加到ArrayList

 
a 
k 
s 

但它仍然錯過了我通過迭代器添加的那個。即我的輸出中缺少r。有沒有辦法使用Iterator將元素添加到ArrayList

import java.util.ArrayList; 
import java.util.ListIterator; 
public class Test 
{ 
public static void main(String args[]) 
{ 
    ArrayList<String> array_test= new ArrayList<String>(); 
    array_test.add("a"); 
    array_test.add("k"); 
    array_test.add("d"); 
    array_test.add("s"); 
    array_test.remove("d"); 
    ListIterator<String> it=array_test.listIterator(); 
    while(it.hasNext()) 
    { 
     String link=it.next(); 
     it.add("r"); 
     System.out.println(link); 

    } 
    //System.out.println("Contents of arrays list "+array_test); 
} 


} 
+0

你期望你的輸出是什麼? – nyxz

回答

1

對不起,我遲到的答覆。這是我如何解決這個問題。

for(ListIterator it=array_test.listIterator();it.hasNext();){ 
String link=it.next(); 
    it.add("r"); 
    it.previous(); 
    it.add("kk"); 
    it.previous(); 
System.out.println(link); 
} 
2

檢查Javadoc。它按照記錄工作。在迭代期間添加元素不會通過迭代器返回該元素,除非您向後退出。

+0

感謝您的重播。我嘗試使用迭代器時無法添加新元素。正如我指定的,我試圖在while循環中添加r。這不起作用。 – prashanth

+2

-1:您應至少引用文檔中的相關部分。 –

+0

它正在工作。您已經註釋的第二個印刷聲明應該包括所有四個字母。 – jbrookover

相關問題