java - "Exception in thread "主 "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"与 ArrayList?

标签 java arraylist

"Exception in thread "main"java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"是我在编译此方法时遇到的主要错误:

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;
}

我该如何解决这个问题?

最佳答案

ArrayList<ArrayList<Integer>> list在第 (0) 位置不包含任何元素,当编译器在指定位置找不到任何元素时,编译器会在迭代时抛出越界异常。

当您尝试执行 list.get(0).set(placeHolder.get(k), (int) (Math.random() * (99999) + 1)); 时语句,您的列表中不包含任何元素。您需要迭代内部列表来设置 list 的值.

关于java - "Exception in thread "主 "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"与 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272508/

相关文章:

java - 生成自签名 ssl 证书作为 Maven 构建的一部分

java - 线程代码中的 NullPointerException 导致线程终止

javascript - 删除输入多个的选定文件名

javascript - 有没有像 set in python 这样的数组方法?

java - Java 中 ArrayList 的合并排序

java - 让java保存HTML文件

java - 在 Eclipse 中激活项目资源管理器的快捷键

java - RichFaces 文件上传抛出 NullPointerException

java - 从 java 中的结果集中返回 arraylist 的 arraylist

java - 如何将多个整数值拆分为索引数组