[java] How can I initialize an ArrayList with all zeroes in Java?

It looks like arraylist is not doing its job for presizing:

// presizing 

ArrayList<Integer> list = new ArrayList<Integer>(60);

Afterwards when I try to access it:

list.get(5) 

Instead of returning 0 it throws IndexOutOfBoundsException: Index 5 out of bounds for length 0.

Is there a way to initialize all elements to 0 of an exact size like what C++ does?

This question is related to java collections

The answer is


// apparently this is broken. Whoops for me!
java.util.Collections.fill(list,new Integer(0));

// this is better
Integer[] data = new Integer[60];
Arrays.fill(data,new Integer(0));
List<Integer> list = Arrays.asList(data);

Java 8 implementation (List initialized with 60 zeroes):

List<Integer> list = IntStream.of(new int[60])
                    .boxed()
                    .collect(Collectors.toList());
  • new int[N] - creates an array filled with zeroes & length N
  • boxed() - each element boxed to an Integer
  • collect(Collectors.toList()) - collects elements of stream

It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.


The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:

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