Search code examples
javaarraysarraylistmultidimensional-arrayguava

adding sublist into guava table in nested loop gives concurrentmodificationerror


There is multidimensional array. I am traversing this array. While traversing I am generating random values and adding into one list in 3rd for loop. After that I am adding each sublist of list into guava table. The first piece of code(there are 3 for loops )running without error. But when I try to print all table I am receiving troublesome error. I can not solve this problem for two days. What can I do?

Table<Integer, Integer, List> paymentAmounts = HashBasedTable.create();
List<Integer> amounts = new ArrayList<Integer>();
int count_begin = 0; //list size
for (int i=0; i<n; i++){
    for(int j=0; j<n; j++){
        if(i != j){
            for(int a=0; a<banksNumberOfOrders[i][j]; a++){         
                int amount = ThreadLocalRandom.current().nextInt(begin1, end1);
                amounts.add(amount);
            }   
            int count_end = count_begin+banksNumberOfOrders[i][j];          
            paymentAmounts.put(i,j,amounts.subList(count_begin, count_end));
            count_begin = count_end;
            System.out.println(i+" --> "+j+" "+paymentAmounts.get(i, j)+" ");
        }   
    }       
    System.out.println();
}

System.out.println(paymentAmounts.cellSet()); //gives concurrent modification error

Solution

  • Change

    paymentAmounts.put(i,j,amounts.subList(count_begin, count_end));
    

    to

    paymentAmounts.put(i,j,new ArrayList<>(amounts.subList(count_begin, count_end)));
    

    You are otherwise inserting just "views" (not copies) of the original amounts list and that causes issues since you are modifying the amounts list after you made that view.

    Same issue as in ConcurrentModificationException thrown by sublist