Home >Java >javaTutorial >What's the Most Efficient Way to Create an ArrayList in Java?

What's the Most Efficient Way to Create an ArrayList in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-29 15:23:11586browse

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:

  • As a List: Simplify the declaration to a regular List type, which avoids the need for the ArrayList constructor.
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
  • Singleton List: For cases with a single element, utilize Collections.singletonList() to create an immutable list.
List<String> places = Collections.singletonList("Buenos Aires");
  • Creating an ArrayList from a List: To obtain a mutable ArrayList from the immutable list, apply the following transformation:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn