“Exception in thread ”main“ java.lang.IndexOutOfBoundsException: Index: 0, Size: 0” with ArrayList?

蓝咒 提交于 2019-12-17 21:08:59

问题


"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?


回答1:


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.

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.




回答2:


Do not use list.set(index, element) on a nonexistent element, since it replaces the old (nonexistent) element with a new one and returns the old one. Instead, use list.add(index, element) and it will work.




回答3:


I thingk u have mistake here

list.get(0).set(placeHolder.get(k), (int) (Math.random() * (99999) + 1));

The java.util.ArrayList.get(int index) method returns the element at the specified position in this list.

You are setting just to first element in the list arrray



来源:https://stackoverflow.com/questions/26272508/exception-in-thread-main-java-lang-indexoutofboundsexception-index-0-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!