2013-06-01 14 views
1

我有一個小問題ListIterator如何修改沒有ConcurrentModificationException的子列表?

我已經開始迭代原始列表[1, 4, 5],我在14之間。然後我修改列表[1, 2, 3, 4, 5]。現在我想重複其餘的原始列表。這裏給出一個示例代碼:

public class Test { 
    public static void main(String[] args) {   
     List<Integer> list = new LinkedList<Integer>(); // [] 
     list.add(new Integer(1)); // [1] 
     list.add(new Integer(4)); // [1, 4] 
     list.add(new Integer(5)); // [1, 4, 5] 
     ListIterator<Integer> iterator = (ListIterator<Integer>) list.iterator(); 

     System.out.println(iterator.next()); // prints [1] 

     // modify subList 
     List<Integer> subList = list.subList(0, 2); // [1, 4] 
     subList.add(1, new Integer(2)); // [1, 2, 4] 
     subList.add(2, new Integer(3)); // [1, 2, 3, 4] 

     // need to print rest of oryginal list: [4, 5] 
     while (iterator.hasNext()) 
      System.out.println(iterator.next()); 
    } 
} 

當我執行它時,我得到java.util.ConcurrentModificationException。你有什麼想法,我該如何正確地做到這一點?

+2

,而你遍歷它不能修改的東西。你將不得不復制修改和遍歷原始文件。 – Colleen

回答

0

如果通過迭代器(而不是通過列表)進行修改名單,那麼你不會得到一個ConcurrentModificationException

System.out.println(iterator.next()); // prints [1] 

    iterator.add(new Integer(2)); // [1, 2, 4] 
    iterator.add(new Integer(3)); // [1, 2, 3, 4] 

    while (iterator.hasNext()) 
     System.out.println(iterator.next()); 
+0

2和3將自動跳過。從關於[ListIterator#add]的文檔(http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#add(E)):「新元素插入隱式遊標:接下來的下一個調用將不受影響,而對之前的後續調用將返回新元素。「 –

+0

當我修改subList時,我沒有訪問原始迭代器的權限。 – WojciechKo

+0

@WojciechKo在這種情況下,另一種選擇是使用[CopyOnWriteArrayList](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html) - 它在快照上返回迭代器,所以他們永遠不會拋出'ConcurrentModificationExceptions'。另一種選擇是使用[ConcurrentLinkedQueue](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html) - 它的迭代器是弱一致的,並且永遠不會拋出' ConcurrentModificationExceptions' –

5

你誤會list.subList使用。

子列表只是原始列表的一部分的視圖。如果你修改子列表,你真的修改了原始列表。

你想要什麼,是複製原始列表的一部分:

List<Integer> subList = new ArrayList<Integer>(list.subList(0,2)); 
相關問題