To initialize a list in Java, you can use the Arrays.asList
method for a fixed-size list or the ArrayList
class for a resizable list.
In this example,
Arrays.asList
method to create a fixed-size list of integers and assign it to the variable fixedSizeList
.Arrays.asList
method takes the elements as arguments and returns a list containing those elements.import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> fixedSizeList = Arrays.asList(1, 2, 3, 4, 5);
System.out.println("Fixed-Size List: " + fixedSizeList);
}
}
Fixed-Size List: [1, 2, 3, 4, 5]
In this example,
ArrayList
class to create a resizable list of strings and assign it to the variable resizableList
.ArrayList
constructor can be called without arguments to create an empty list or with a collection to initialize the list with elements.add
method.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> resizableList = new ArrayList<>();
resizableList.add("Apple");
resizableList.add("Banana");
resizableList.add("Cherry");
resizableList.add("Date");
System.out.println("Resizable List: " + resizableList);
}
}
Resizable List: [Apple, Banana, Cherry, Date]
In this tutorial, we learned How to Initialize a List in Java language with well detailed examples.