One-Line Initialization of an ArrayList
Initializing an ArrayList with multiple values can be a time-consuming process, especially if you have a large list of items. The following code snippet shows how to initialize an ArrayList with multiple values in just one line:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
This method takes advantage of the Arrays.asList() method, which converts an array of values into a list. By passing the array of values directly into the constructor of the ArrayList, we can create an ArrayList with multiple values in a single line of code.
Optimizing the Initialization
While the above method is convenient, it can be further optimized if the list does not need to be mutable. If the list is immutable, we can use the Collections.singletonList() method instead. This method creates an immutable list that contains a single element.
List<String> places = Collections.singletonList("Buenos Aires");
Creating a Mutable ArrayList
If you need to create a mutable ArrayList, you can use the following method:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
This method creates a mutable ArrayList by converting the immutable list created by Arrays.asList() into a mutable ArrayList.
Importing the Correct Package
Remember to import the java.util.Arrays package when using the Arrays.asList() method.
import java.util.Arrays;
The above is the detailed content of How Can I Efficiently Initialize an ArrayList in Java with Multiple Values?. For more information, please follow other related articles on the PHP Chinese website!