简体   繁体   中英

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.

Thanks in advance.

list.add(newList); this line should be outside your for loop. You are trying to modify your list while iterating on it. Just keep adding elements to newList in the for loop. Add the line list.add(newList); after the for loop.

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) {

with:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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