在嵌套循环中将子列表添加到 guava table 中会出现 concurrentmodificationerror
adding sublist into guava table in nested loop gives concurrentmodificationerror
存在多维数组。我正在遍历这个数组。遍历时我生成随机值并添加到第三个 for 循环中的一个列表中。之后,我将列表的每个子列表添加到 guava table。第一段代码(有3个for循环)运行没有错误。但是当我尝试打印所有 table 时,我收到了麻烦的错误。我这两天解决不了这个问题。我能做什么?
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
改变
paymentAmounts.put(i,j,amounts.subList(count_begin, count_end));
到
paymentAmounts.put(i,j,new ArrayList<>(amounts.subList(count_begin, count_end)));
否则您只是插入原始 amounts
列表的 "views"(而非副本),这会导致问题,因为您在创建该视图后正在修改 amounts
列表。
与 ConcurrentModificationException thrown by sublist
中的问题相同
存在多维数组。我正在遍历这个数组。遍历时我生成随机值并添加到第三个 for 循环中的一个列表中。之后,我将列表的每个子列表添加到 guava table。第一段代码(有3个for循环)运行没有错误。但是当我尝试打印所有 table 时,我收到了麻烦的错误。我这两天解决不了这个问题。我能做什么?
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
改变
paymentAmounts.put(i,j,amounts.subList(count_begin, count_end));
到
paymentAmounts.put(i,j,new ArrayList<>(amounts.subList(count_begin, count_end)));
否则您只是插入原始 amounts
列表的 "views"(而非副本),这会导致问题,因为您在创建该视图后正在修改 amounts
列表。
与 ConcurrentModificationException thrown by sublist
中的问题相同