Home >Java >javaTutorial >How Can I Efficiently Initialize an ArrayList in Java?

How Can I Efficiently Initialize an ArrayList in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 22:56:15297browse

How Can I Efficiently Initialize an ArrayList in Java?

Initialization of an ArrayList in One Line

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!

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