java - 迭代列表的列表

标签 java iterator sublist

我正在尝试迭代列表操作系统列表,但我总是得到 CME,甚至在迭代列表时使用迭代器删除和添加元素。

我在社区中搜索了类似的问题,但我发现的问题对我没有帮助。真的希望你们能帮助我弄清楚如何做我需要做的事情。

我有我ListIterator<List<Event<T>>> itrListsEvent = partitionSubLists.listIterator(); partitionSubLists是 A list of lists 。所以我有一个更大的列表,其中有四个子列表。

我需要迭代子列表,在迭代时删除和添加元素。完成第一个子列表的迭代后,我需要继续迭代第二个子列表,依此类推。

这是我到目前为止所做的:

  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<>());

关于java - 迭代列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61087282/

相关文章:

java - Wicket 面板中的 Ajax 不起作用

c++ - 为什么随机访问迭代器的算术运算符接受/返回 int 而不是 size_t?

c++ - boost::transform_iterator 和 std::iter_swap

Python - 将部分子列表的元素转换为 int

position - Lisp - 从位置移除

java - 写入文本文件时格式化数据 (Java)

java - 阅读发送到电话号码的短信

java - ProGuard 配置文件不起作用

arrays - Swift 中带有数组的 For-In 循环中迭代器元素的可变性

python - 从另一个字典中提取带有值子集的字典