[英]Iterating over List of Lists
我正在尝试迭代列表操作系统列表,但我一直在使用 CME,即使在迭代列表时使用 Iterator 删除和添加元素。
我在社区中搜索了类似的问题,但我发现的那些对我没有帮助。 真的希望你们帮助我弄清楚如何做我需要做的事情。
我有我ListIterator<List<Event<T>>> itrListsEvent = partitionSubLists.listIterator();
partitionSubLists
是list 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.