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

How Can I Efficiently Initialize an ArrayList in Java with Multiple Values?

Mary-Kate Olsen
Release: 2024-12-31 03:29:09
Original
127 people have browsed it

How Can I Efficiently Initialize an ArrayList in Java with Multiple Values?

One-Line Initialization of an ArrayList

Initializing an ArrayList with multiple values can be a time-consuming process, especially if you have a large list of items. The following code snippet shows how to initialize an ArrayList with multiple values in just one line:

ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Copy after login
Copy after login

This method takes advantage of the Arrays.asList() method, which converts an array of values into a list. By passing the array of values directly into the constructor of the ArrayList, we can create an ArrayList with multiple values in a single line of code.

Optimizing the Initialization

While the above method is convenient, it can be further optimized if the list does not need to be mutable. If the list is immutable, we can use the Collections.singletonList() method instead. This method creates an immutable list that contains a single element.

List<String> places = Collections.singletonList("Buenos Aires");
Copy after login

Creating a Mutable ArrayList

If you need to create a mutable ArrayList, you can use the following method:

ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Copy after login
Copy after login

This method creates a mutable ArrayList by converting the immutable list created by Arrays.asList() into a mutable ArrayList.

Importing the Correct Package

Remember to import the java.util.Arrays package when using the Arrays.asList() method.

import java.util.Arrays;
Copy after login

The above is the detailed content of How Can I Efficiently Initialize an ArrayList in Java with Multiple Values?. 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