The Java ArrayList can be initialized in a number of ways depending on the requirement. In this tutorial, we will learn to initialize ArrayList based on some frequently seen usecases.
1. Initialize ArrayList in One Line
Creating and initializing the ArrayList in different statements sometimes seems to generate unnecessary boilerplate code. We can optimize the ArrayList creation using the following ways.
1.1. Using Arrays.asList() – Initialize ArrayList from Array
To initialize an ArrayList in a single line statement, get all elements in form of array using
Arrays.asList method and pass the array argument to
ArrayList<String> names = new ArrayList<String>( Arrays.asList("alex", "brian", "charles") );
1.2. Unmodifiable Lists using List.of() – Java 9
We can use
List.of() static factory methods to create unmodifiable lists. The only drawback is that add() operation is not supported in these lists.
List<String> names = List.of("alex", "brian", "charles");
2. Using ArrayList Constructor
Using ArrayList constructor is the traditional approach. The new ArrayList() constructor takes an optional parameter initialCapacity. It must be a positive integer and denotes the initial capacity of the list.
We create a blank ArrayList using the constructor and add elements to the list using add() method.
ArrayList<String> names = new ArrayList<>(); names.add("alex"); //Adding a single element at a time names.add("brian"); names.add("charles");
We can add elements one by one or pass another collection to addAll() elements in one step.
HashMap<String, Integer> details = new HashMap<>(); details.put("keanu", 23); details.put("max", 24); details.put("john", 53); names.addAll(details.keySet()); //Adding multiple elements in ArrayList
That’s all about creating an ArrayList in Java. Drop me your questions in the comments.
Happy Learning !!
Leave a Reply