Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initiallizing Values of ArrayList<Integer> with zeroes - Java

Tags:

java

arraylist

I have an ArrayList array with a specified max capacity M and I want to initialize that array by filling it with zero values. Therefore I use the following code:

for(int i = 0; i < array.size(); i++) {

    array.add(i, 0);

}

However, this does not work. I get an indexOutOfBoundsException: Index: 0, Size: 0

Indeed, I printed the array after that loop in order to test if it is filled with values but the result is an empty array: [].

Clearly, there is some important concept that I don't know. I am sure that the solution is simple but I miss some fundamental insight of the concept.

like image 569
Kotsos Avatar asked Dec 08 '22 09:12

Kotsos


2 Answers

To initialize an ArrayList with 100 zeros you do:

ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(100, 0));
like image 84
Tharindu Kumara Avatar answered Mar 06 '23 20:03

Tharindu Kumara


Change array.add(i, 0) to array.add(0);.

You cannot add to those specified indices unless the size of the ArrayList is larger or equal since those indices don't exist.

Also you'll have to change your for loop as well since its size is not 100; it is 0. This is because when you declare array = new ArrayList<Integer>(100), you're only specifying how much memory should be reserved for it - not its size. Its size is still 0 and will grow only when you add elements.

like image 36
u3l Avatar answered Mar 06 '23 21:03

u3l