In this write-up, we will cover the below-listed approaches to initialize an ArrayList in Java:
- How to declare/initialize an empty ArrayList?
- How to use Arrays.asList() method to initialize an ArrayList
- How to use add() method to initialize an ArrayList?
- How to use List.of() method to initialize an ArrayList?
So let’s begin!
How to declare/initialize an empty ArrayList?
In Java, if we didn’t specify any argument to the ArrayList constructor, then it will be initialized as an empty ArrayList as shown in the below-given snippet:
The above-given piece of code will create an empty ArrayList.
How to use Arrays.asList() method to initialize an ArrayList
To initialize an ArrayList in Java, we can specify the collection of elements as an argument to the constructor of ArrayList using the Arrays.list method as shown in the below-given code block:
languages.forEach(itemsList -> {
System.out.println(itemsList);
});
In the above-given program, firstly, we initialized a collection of elements using asList() method and afterward we utilized the forEach() method traverse through each element of the ArrayList:
The above snippet verified the working of asList() method.
How to use add() method to initialize an ArrayList?
In Java, the most common and the easiest way to initialize an ArrayList is the add() method as shown in the below-given code snippet:
languages.add("Java");
languages.add("PHP");
languages.add("C++");
languages.add("JavaScript");
languages.add("Python");
languages.forEach(itemsList -> {
System.out.println(itemsList);
});
In this example program, we utilized the add() method to initialize the ArrayList elements one-by-one. Next, we utilized the forEach() method to iterate each element of the list:
This is how the add() method is used to initialize the ArrayList in Java.
How to use List.of() method to initialize an ArrayList?
Java provides another useful method named List.of() that can be used to initialize an ArrayList:
languages.forEach(itemsList -> {
System.out.println(itemsList);
});
In this example, we utilized the List.of() method to initialize the ArrayList in Java:
This is how List.of() method works in Java.
Conclusion
In Java, several methods like add(), List.of(), and Arrays.asList() can be used to initialize an ArrayList. forEach() method can be used to traverse the list elements. Using these methods, we can initialize any type of ArrayList i.e. integer, String, or any other object. In this write-up, we explained how to initialize an ArrayList in Java using different approaches such as using add() method, constructor, List.of(), and Array.asList() method.