Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arraylist

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

like image 736
Jake Urban Avatar asked Oct 28 '25 04:10

Jake Urban


1 Answers

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.

like image 117
Santhosh Avatar answered Oct 29 '25 19:10

Santhosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!