This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: Initialize an ArrayList with one line

I want to create a list of options for testing purposes. First, I do this:

ArrayList places = new ArrayList(); places.add(“Buenos Aires”); Places. The add (” Cordoba “); places.add(“La Plata”);

I then refactor the code as follows:

ArrayList Places = new ArrayList(Arrays. AsList (“Buenos Aires”, “Cordoba “, “La Plata”));

Is there a better way?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

Simple answer Java 10 or later:

var strings = List.of("foo", "bar", "baz");

Copy the code

This will give you an immutable List that cannot be changed. In most cases, this is what you want.

Java 9

If you are using Java 9, you cannot use the var keyword:


List<String> strings = List.of("foo", "bar", "baz");

Copy the code

Java 8 or earlier:

List<String> strings = Arrays.asList("foo", "bar", "baz");
Copy the code

This will give you List*, backed up with an array, so it cannot change the length.

* Implementation details: This is a private nested java.util.ArrayList class called Java.util.arrayList, which is different from the java.util.arrayList class despite having the same simple name. Static imports

You can make Java 8 shorter with arrays.asList static imports:

import static java.util.Arrays.asList; . List<String> strings = asList("foo", "bar", "baz");Copy the code

Any modern IDE * will give you advice and help.

I don’t recommend statically importing the static list. of method as just of, because it can be confusing.

* For example, in IntelliJ IDEA, press Alt+Enter and select Static Import Method… Use Streams

Why does it have to be a List? In Java 8 and later, you can use Stream to be more flexible:


Stream<String> strings = Stream.of("foo", "bar", "baz");
Copy the code

You can concatenate the Stream:

Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
                                       Stream.of("baz", "qux"));
Copy the code

Alternatively, you can go from Stream to List:

import static java.util.stream.Collectors.toList; . var strings = Stream.of("foo", "bar", "baz").toList(); // Java 16 List<String> strings = Stream.of("foo", "bar", "baz").collect(toList()); // Java 8Copy the code

But it is better to use a Stream rather than collect it into a List. If you specifically need java.util.arrayList *

If you want to prepopulate both the ArrayList and add to it after, use it

List<String> strings = new ArrayList<>(List.of("foo", "bar"));
strings.add("baz");

Copy the code

Or in Java 8 or earlier:

List<String> strings = new ArrayList<>(asList("foo", "bar"));
strings.add("baz");
Copy the code

Or use Stream:

import static java.util.stream.Collectors.toCollection;

List<String> strings = Stream.of("foo", "bar")
                             .collect(toCollection(ArrayList::new));
strings.add("baz");

Copy the code

But again, it is better for streams to use Direct rather than collect them into a List.

* You probably don’t need a special ArrayList. Quote JEP 269:

There are a few use cases for initializing mutable collection instances with predefined value sets. It is usually best to place these predefined values in an immutable collection and then initialize the mutable collection through the copy constructor.Copy the code

(emphasis mine) program interface, not implementation

You said ArrayList declared the List as in code, but you should only do List if you use an ArrayList that is not a member of IN.

You most likely won’t.

In general you should only use generic interfaces that you use (such as declaring variables Iterable, Collection, or List) and initialize them with specific implementations (such as ArrayList, LinkedList, or arrays.asList ()).

Otherwise, you’ll limit your code to that particular type, and it will be hard to change when needed.

For example, if you’re passing an ArrayList to void Method (…) :

// Iterable if you just need iteration, for (String s : strings): void method(Iterable<String> strings) { for (String s : strings) { ... } } // Collection if you also need .size(), .isEmpty(), or .stream(): void method(Collection<String> strings) { if (! strings.isEmpty()) { strings.stream()... } } // List if you also need .get(index): void method(List<String> strings) { strings.get(...) } // Don't declare a specific list implementation // unless you're sure you need it: void method(ArrayList<String> strings) { ??? // You don't want to limit yourself to just ArrayList }Copy the code

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 2…

The authors’ advice: Use whichever version you’re using. You can put x in a stream


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️