简体   繁体   English

java 2d arraylist循环内编辑

[英]java 2d arraylist edit inside loop

I have a 2d ArrayList which stores objects, i want to check if a certain object exists in any of of the rows, and if not add a new row, and search that object in future checks. 我有一个存储对象的二维数组列表,我想检查某个对象是否存在于任何行中,如果不添加新行,并在以后的检查中搜索该对象。 eg. 例如。

ArrayList<List<Object>> list = new ArrayList<>();
for(List<Object> o : list) {
    if(!o.contains(object){
        ArrayList<Object> newList = new ArrayList<>();
        newList.add(object);
        list.add(newList);
    }
}

This gives me a 'ConcurrentModificationException' but I can't find another way to do it. 这给了我一个'ConcurrentModificationException',但是我找不到另一种方法。

Thanks in advance. 提前致谢。

list.add(newList); list.add(newList); this line should be outside your for loop. 这行应该在您的for循环之外。 You are trying to modify your list while iterating on it. 您正在尝试在迭代列表时对其进行修改。 Just keep adding elements to newList in the for loop. 只需继续在for循环中向newList添加元素。 Add the line list.add(newList); 添加行list.add(newList); after the for loop. 在for循环之后。

You cannot change a List while you are iterating over its items. 迭代列表时,不能更改列表。

What you can do is: 您可以做的是:

ArrayList<List<Object>> list = new ArrayList<>(); // in practice this would not be an empty list, but it would, as in your example, contain all items
ArrayList<List<Object>> newRows = new ArrayList<>();
for(List<Object> o : list) {
    if(!o.contains(object){
        ArrayList<Object> newList = new ArrayList<>();
        newList.add(object);
        newRows.add(newList);
    }
}
list.addAll(newRows);

You have to replace: 您必须更换:

for(List o : list) { for(列表o:列表){

with: 与:

for(int i = 0; i < list.size(); i++) { List o = list.get(i); for(int i = 0; i <list.size(); i ++){List o = list.get(i);

Just be careful when you do this to handle how you modify the list. 执行此操作时要小心,以处理修改列表的方式。 In this case there should be no problem. 在这种情况下,应该没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM