Create an Empty ArrayList in Java
To create an Empty ArrayList in Java, you can use new keyword and ArrayList constructor with no arguments passed to it.
Following is the syntax to create an empty ArrayList.
ArrayList<T> myList = new ArrayList<T>();
Example 1 – Create an Empty ArrayList of Strings
In the following example, we shall create an empty ArrayList of Strings.
Java Program
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<String>(); } }
names
is an empty ArrayList that can store String elements.
ADVERTISEMENT
Example 2 – Create an Empty ArrayList of Objects
In the following example, we shall create an empty ArrayList that can store Car type objects.
Java Program
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList<Car> cars = new ArrayList<Car>(); } } class Car { public String name; public int miles; }
cars
is an empty ArrayList that can store Car objects.
Conclusion
In this Java Tutorial, we have learned how to create an empty ArrayList in Java.