"线程"main"中的异常; java.lang.IndexOutOfBoundsException:索引:0,大小:0"与ArrayList? [英] "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" with ArrayList?

查看:64
本文介绍了"线程"main"中的异常; java.lang.IndexOutOfBoundsException:索引:0,大小:0"与ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

线程"main"中的异常java.lang.IndexOutOfBoundsException:索引:0,大小: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;
}

我该如何解决?

推荐答案

ArrayList<ArrayList<Integer>> list在第(0)个位置中不包含任何元素,并且编译器在无法在第(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.

这篇关于&quot;线程"main"中的异常; java.lang.IndexOutOfBoundsException:索引:0,大小:0&quot;与ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆