Initialize an ArrayList in Java
To initialize an ArrayList in Java, you can create a new ArrayList with new keyword and ArrayList constructor. You may optionally pass a collection of elements, to ArrayList constructor, to add the elements to this ArrayList. Or you may use add() method to add elements to the ArrayList.
In this tutorial, we will go through some of these methods to initialize an ArrayList.
Initialize Empty ArrayList
You can initialize an empty ArrayList by passing no argument to the ArrayList constructor.
In the following example, we create an ArrayList that can store strings.
Java Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> arraylist_1 = new ArrayList<String>();
}
}
You may add elements to this ArrayList after initialization using add() method.
Java Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> arraylist_1 = new ArrayList<String>();
arraylist_1.add("apple");
arraylist_1.add("banana");
arraylist_1.forEach(element -> {
System.out.println(element);
});
}
}
Output
apple
banana
Initialize ArrayList with a Collection of Elements
You may specify a collection as argument to ArrayList constructor, and the new ArrayList will be initialized with elements in the collection.
Java Program
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListExample {
public static void main(String[] args) {
String[] arr = {"apple", "banana"};
ArrayList<String> arraylist_1 = new ArrayList<String>(Arrays.asList(arr));
arraylist_1.forEach(element -> {
System.out.println(element);
});
}
}
Output
apple
banana
Conclusion
In this Java Tutorial, we learned how to initialize an ArrayList using its constructor, with the help of example programs.