Kotsos
Kotsos

Reputation: 329

Initiallizing Values of ArrayList<Integer> with zeroes - Java

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.

Upvotes: 4

Views: 1301

Answers (3)

u3l
u3l

Reputation: 3412

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.

Upvotes: 3

user3312748
user3312748

Reputation: 53

You can also make the list to 0 values by this code, after initializing the arraylist

for (int i = 0; i < 60; i++) {
    list.add(0);
}

Upvotes: 2

Tharindu Kumara
Tharindu Kumara

Reputation: 4458

To initialize an ArrayList with 100 zeros you do:

ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(100, 0));

Upvotes: 11

Related Questions