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

How Can I Efficiently Initialize an ArrayList in Java?

Mary-Kate Olsen
Release: 2024-12-18 22:56:15
Original
294 people have browsed it

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"));
Copy after login
Copy after login

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");
Copy after login

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"));
Copy after login
Copy after login

Remember to include the necessary package import statement:

import java.util.Arrays;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template