Home >Java >javaTutorial >What's the Most Efficient Way to Create an ArrayList in Java?
Creating an ArrayList with Minimal Effort
One common task in programming involves creating a list for testing or other purposes. Traditionally, this involved an initialization and a series of subsequent add() operations:
ArrayList<String> places = new ArrayList<String>(); places.add("Buenos Aires"); places.add("Córdoba"); places.add("La Plata");
Recognizing the repetitive nature of this approach, an improved version emerged:
ArrayList<String> places = new ArrayList<String>( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Exploring Alternative Strategies
As it turns out, there are even more concise ways to achieve the same result:
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
List<String> places = Collections.singletonList("Buenos Aires");
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Remember to import the necessary Java package:
import java.util.Arrays;
Choosing the Optimal Solution
The preferred method depends on the specific requirements of your application. For an immutable list, opt for the simpler List declaration or Collections.singletonList(). When mutability is essential, employ the transformation from an immutable list to an ArrayList.
The above is the detailed content of What's the Most Efficient Way to Create an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!