2013-09-26 117 views
0

我已經編寫了以下使用的ListIterator將元素添加到空表:如何使用ListIterator將元素添加到空列表中?

ArrayList<String> list = new ArrayList<String>(); 
ListIterator<String> listIterator = list.listIterator(); 

public void append(String... tokens) { 

     if(tokens == null) 
      return; 

     // append tokens at the end of the stream using the list iterator 
     for(int i = 0 ; i < tokens.length ; ++i){ 

      // if the token is not null we append it 
      if(tokens[i] != null && !tokens[i].equals("")) 
       listIterator.add(tokens[i]); 
     } 

     reset(); 
    } 

我要添加使用的ListIterator元素到此空列表,然後將所有的元素後,我想移動的迭代器到列表的開頭,我也希望能夠刪除迭代器指向的元素,出於某種原因,我的方法似乎不工作,請幫助。

回答

2

也許我不理解你的問題,但它好像你真的想...

list.add(tokens[i]); 

的,而不是...

listIterator.add(tokens[i]); 
+0

其實我是想爲什麼我使用的ListIterator – AnkitSablok

+0

你能具體談談什麼是不工作添加使用的ListIterator避免ConcurrentModificationException的元素的迭代器,那是什麼?一個可能的錯誤(可能是它的意圖)是++,而不是i ++。 –

0

在添加完項目後到迭代器,獲取迭代器的新實例並重新開始。 reset()方法應該做什麼?

除非修改正在循環的列表,否則不會得到ConcurrentModificationException。

也許這就是你要找的。

ArrayList<String> list = new ArrayList<String>(); 
    ListIterator<String> listIterator = list.listIterator(); 
    String[] tokens = {"test", "test1", "test2"}; 

    // append tokens at the end of the stream using the list iterator 
    for (int i = 0; i < tokens.length; ++i) { 

     // if the token is not null we append it 
     if (tokens[i] != null && !tokens[i].equals("")) 
      listIterator.add(tokens[i]); 
    } 

    while (listIterator.hasPrevious()) { 
     if(listIterator.previous().toString().equals("test1")) { 
      listIterator.remove(); 
     } 
    } 

    while (listIterator.hasNext()) { 
     System.out.println(listIterator.next().toString()); 
    } 
+0

重置方法用於將迭代器設置爲列表的開頭 – AnkitSablok

+0

它是否返回一個新的迭代器?你如何重置它? – SuperCamp

+0

while(listIterator.hasPrevious())listIterator.previous(); – AnkitSablok