Initialize an arrayList with zeros
16,036
Solution 1
You can use Collections.fill(List<? super T> list,T obj)
method to fill your list with zeros. In your case you are setting new ArrayList<>(40)
here 40
is not length of the list but the initial capacity. You can use array to build your list with all zeros in it. Checkout following piece of code.
ArrayList<Integer> myList= new ArrayList<>(Arrays.asList(new Integer[40]));
Collections.fill(myList, 0);//fills all 40 entries with 0"
System.out.println(myList);
OUTPUT
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Solution 2
Use .add(0)
instead. The ArrayList(int capacity)
constructor sets an initial capacity, but not initial items. So your list is still empty.
Author by
yaylitzis
Updated on July 27, 2022Comments
-
yaylitzis almost 2 years
I am creating an
ArrayList
and its size is40
ArrayList<Integer> myList= new ArrayList<>(40);
How can I initialize
myList
with zeros0
? I tried thisfor(int i=0; i<40; i++){ myList.set(i, 0); }
but I get
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0