Initialize an arrayList with zeros

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]

Try Collections.nCopies():

ArrayList<Integer> myList = new ArrayList<Integer>(Collections.nCopies(40, 0));

OR:

List<Integer> myList = Collections.nCopies(40, 0);

See doc


Use .add(0) instead. The ArrayList(int capacity) constructor sets an initial capacity, but not initial items. So your list is still empty.