java - Initialization of an ArrayList in one line

ID : 183

viewed : 356

Tags : javacollectionsarraylistinitializationjava-9java

Top 5 Answer for java - Initialization of an ArrayList in one line

vote vote


It would be simpler if you were to just declare it as a List - does it have to be an ArrayList?

List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata"); 

Or if you have only one element:

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

This would mean that places is immutable (trying to change it will cause an UnsupportedOperationException exception to be thrown).

To make a mutable list that is a concrete ArrayList you can create an ArrayList from the immutable list:

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


Actually, probably the "best" way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way:

ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); 

The catch is that there is quite a bit of typing required to refer to that list instance.

There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):

ArrayList<String> list = new ArrayList<String>() {{     add("A");     add("B");     add("C"); }}; 

However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.

What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):

List<String> list = ["A", "B", "C"]; 

Unfortunately it won't help you here, as it will initialize an immutable List rather than an ArrayList, and furthermore, it's not available yet, if it ever will be.

vote vote


The simple answer

Java 10 or later:

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

This will give you an immutable List, so it cannot be changed.
Which is what you want in most cases where you're prepopulating it.

Java 9

If you're using Java 9, you can't use the var keyword:

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

Java 8 or earlier:

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

This will give you a List* backed by an array, so it cannot change length.
But you can call List.set(...), so it's still mutable.

* Implementation detail: It's a private nested class inside java.util.Arrays, named ArrayList,
which is a different class from java.util.ArrayList, even though their simple names are the same.

Static import

You can make Java 8 Arrays.asList even shorter with a static import:

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

Any modern IDE* will suggest and do this for you.

I don't recommend statically importing the List.of method as just of, because it's confusing.

* For example, in IntelliJ IDEA you press Alt+Enter and select Static import method...

Using Streams

Why does it have to be a List?
With Java 8 or later you can use a Stream which is more flexible:

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

You can concatenate Streams:

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

Or you can go from a Stream to a List:

import static; ... var strings = Stream.of("foo", "bar", "baz").toList(); // Java 16  List<String> strings = Stream.of("foo", "bar", "baz").collect(toList()); // Java 8 

But preferably, just use the Stream without collecting it to a List.

If you specifically need a java.util.ArrayList*

If you want to both prepopulate an ArrayList and add to it afterwards, use

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

or in Java 8 or earlier:

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

or using Stream:

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

But again, it's better to just use the Stream directly instead of collecting it to a List.

*You probably don't need specifically an ArrayList. To quote JEP 269:

There is a small set of use cases for initializing a mutable collection instance with a predefined set of values. It's usually preferable to have those predefined values be in an immutable collection, and then to initialize the mutable collection via a copy constructor.

(emphasis mine)

Program to interfaces, not to implementations

You said you've declared the list as an ArrayList in your code, but you should only do that if you're using some member of ArrayList that's not in List.

Which you are most likely not doing.

Usually you should just declare variables by the most general interface that you are going to use (e.g. Iterable, Collection, or List), and initialize them with the specific implementation (e.g. ArrayList, LinkedList or Arrays.asList()).

Otherwise you're limiting your code to that specific type, and it'll be harder to change when you want to.

For example, if you're passing an ArrayList to a 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()) { } }  // List if you also need random access, .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 } 

Another example would be always declaring variable an InputStream even though it is usually a FileInputStream or a BufferedInputStream, because one day soon you or somebody else will want to use some other kind of InputStream.

vote vote


If you need a simple list of size 1:

List<String> strings = new ArrayList<String>(Collections.singletonList("A")); 

If you need a list of several objects:

List<String> strings = new ArrayList<String>(); Collections.addAll(strings,"A","B","C","D"); 
vote vote


With Guava you can write:

ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata"); 

In Guava there are also other useful static constructors. You can read about them here.

Top 3 video Explaining java - Initialization of an ArrayList in one line