To create a list of size N in Java, you can use the Arrays.asList
method or the Collections.nCopies
method.
In this example,
Arrays.asList
method with an array of default values to create a list of size N.Arrays.asList
method returns a fixed-size list backed by the specified array.import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int size = 5;
Integer[] array = new Integer[size];
Arrays.fill(array, 0);
java.util.List<Integer> list = Arrays.asList(array);
System.out.println("List of size " + size + " with default values: " + list);
}
}
List of size 5 with default values: [0, 0, 0, 0, 0]
In this example,
Collections.nCopies
method to create an immutable list containing N copies of the specified object.Collections.nCopies
method returns a fixed-size list that contains N copies of the specified object.import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
int size = 5;
List<String> list = Collections.nCopies(size, "");
System.out.println("List of size " + size + " with default values: " + list);
}
}
List of size 5 with default values: [, , , , ]
In this tutorial, we learned How to create a List of size N in Java language with well detailed examples.