簡體   English   中英

迭代列表列表

[英]Iterating over List of Lists

我正在嘗試迭代列表操作系統列表,但我一直在使用 CME,即使在迭代列表時使用 Iterator 刪除和添加元素。

我在社區中搜索了類似的問題,但我發現的那些對我沒有幫助。 真的希望你們幫助我弄清楚如何做我需要做的事情。

我有我ListIterator<List<Event<T>>> itrListsEvent = partitionSubLists.listIterator(); partitionSubListslist of lists 所以我有一個更大的列表,里面有四個子列表。

我需要遍歷子列表,並在迭代時刪除和添加元素。 完成對第一個子列表的迭代后,我需要 go 轉發以迭代第二個子列表,依此類推。

這是我到目前為止所做的:

  public List<List<Event<T>>> partitionedLists (List<Event<T>> list)
    {     
        int listSize = list.size();
        int partitionSize = listSize / 4;

        List<List<Event<T>>> partitions = new ArrayList<>();

        for (int i = 0; i < listSize; i += partitionSize) 
        {
            partitions.add(list.subList(i, Math.min(i + partitionSize, list.size())));
        }        
        return partitions;        
    }

List<List<Event<T>>> partitionSubLists     = partitionedLists(List<Event<T>>);
ListIterator<List<Event<T>>> itrListsEvent = partitionSubLists.listIterator();

while(itrListsEvent.hasNext())
{
       List<PrefixEvent<T>> listPE  = new ArrayList<Event<T>>();            
       listPE   = itrListsPrefixEvent.next(); 
       ListIterator<Event<T>> itrEvent = listPE.listIterator();

       while(itrEvent.hasNext())
       {
          //here I remove and add elements inside the sublist.
          //when finished, I need to go back to first while and go forward to the next sublists
          //and in this moment, i got ConcurrentModificationException

         itrEvent.remove()
            .
            . 
            .
        // some code here

         itrEvent.add(new Event<T>);
       }

}

目前還不清楚您要達到的目標。 據我了解,您可以這樣實現:

List<PrefixEvent<T>>  listPE   = itrListsPrefixEvent.next();
// No iterator.

for (int i = 0; i < listPE.size(); ++i) {
  listPE.remove(i);

  // some code here

  listPE.add(i, new Event<>());
}

這避免了 ConcurrentModificationException,因為您在創建迭代器后不會在結構上修改列表。

如果您實際上不需要itrEvent.remove()itrEvent.add(new Event<T>())之間的“刪除一個元素”列表,則可以繼續使用ListIterator ,然后將值設置為一個新值:

itrEvent.set(new Event<>());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM