How to set a default value for items list?

You can try:

List<Integer> list1 = Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

There are 10 zeroes. You need to know the number of elements at the compile time, but you have only one line. If you don't know the number of elements at compile time, then you can use the suggested Arrays.fill() approach.


Maybe you just need an array?

int[] array = new int[10];

You need a list if you need to change the size of it dynamically. If you don't need this feature, an array may suit your needs, and it will automatically initialize all the values to 0 for you.


Collections.nCopies is your friend if you need a list instead of an array:

List<Integer> list = Collections.nCopies(10, 0);

If a mutable list is needed, wrap it:

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

Arrays.fill lets you avoid the loop.

Integer[] integers = new Integer[10];
Arrays.fill(integers, 0);
List<Integer> integerList = Arrays.asList(integers);

Tags:

Java