“线程“main"中的异常java.lang.IndexOutOfBoundsException:索引:0,大小:0"与 ArrayList? [英] "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" with ArrayList?
问题描述
线程main"中的异常 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" 是我编译此方法时遇到的主要错误:
"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" is the main error I get when I compile this method:
public static ArrayList<ArrayList<Integer>> createSparseArray(int len, double den) {
int counter = 0;
ArrayList<Integer> placeHolder = new ArrayList<Integer>();
for (int j = 0; j < len; j++) {
double randomNumber = Math.random();
if (randomNumber < den) {
counter++;
placeHolder.add(j);
}
}
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
for (int k = 0; k < counter; k++) {
for (int m = 0; m < 2; m++) {
list.get(0).set(placeHolder.get(k), (int) (Math.random() * (99999) + 1));
}
}
return list;
}
我该如何解决这个问题?
How can I fix this?
推荐答案
ArrayList
在第 (0) 个位置不包含任何元素,当在指定位置找不到任何元素时,编译器在迭代时抛出越界异常.
ArrayList<ArrayList<Integer>> list
doesnt contain any element in (0)th postion and the compiler throws out of bounds exception on iterating when it doesn't find any element in the specified postion.
当您尝试执行 list.get(0).set(placeHolder.get(k), (int) (Math.random() * (99999) + 1));
语句时,您的列表中不包含任何元素.您需要迭代内部列表以设置 list
的值.
when you try executing list.get(0).set(placeHolder.get(k), (int) (Math.random() * (99999) + 1));
statement , your list doesnt contain any element inside it. you need to iterate the inner list to set the values for the list
.
这篇关于“线程“main"中的异常java.lang.IndexOutOfBoundsException:索引:0,大小:0"与 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!