Initializing ArrayList <Integer> Values ​​with Zeros - Java

I have an ArrayList array with the indicated maximum capacity M, and I want to initialize this array by filling it with null 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 indexOutOfBoundsException: Index: 0, Size: 0

In fact, I printed the array after this loop to check if it is filled with values, but the result is an empty array: [].

It is clear that there is some important concept that I do not know. I am sure the solution is simple, but I lack a fundamental understanding of the concept.

+4
source share
3 answers

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

, ArrayList , .

for, 100; 0. , , array = new ArrayList<Integer>(100), , , . - 0 .

+3

ArrayList 100 , :

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

You can also make list 0 the values ​​of this code after initializing arraylist

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

Source: https://habr.com/ru/post/1527160/


All Articles