Home >Java >javaTutorial >How Can I Efficiently Initialize an ArrayList in Java?
Initializing an ArrayList can be done in various ways, striving for both brevity and efficiency. While the initial approach of creating an empty ArrayList and subsequently adding elements works, a more efficient method is to use the Arrays.asList() function. This function takes a list of elements as input and returns an immutable list representation of those elements.
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
For scenarios involving a single element, consider using the immutable Collections.singletonList() method. This simplifies the code and ensures immutability:
List<String> places = Collections.singletonList("Buenos Aires");
For situations where mutability is desired within an ArrayList, a concrete ArrayList can be created from the immutable list:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Remember to include the necessary package import statement:
import java.util.Arrays;
To summarize, the most optimal method depends on the desired immutability and mutability properties. For immutable lists, Arrays.asList() is preferred, while Collections.singletonList() is ideal for single-element lists. For mutable lists, an ArrayList can be created from the immutable list.
The above is the detailed content of How Can I Efficiently Initialize an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!