Best Way to Initialization ArrayList in one line | Java List

Actually, probably the “best” way to initialize the ArrayList is the method is no needed to create a new List in any way. There are many ways to do because of java versions are changed, First, wee the way then decide which is the Best Way to Initialization ArrayList in one line.

Normal Way:- Multiline

See below only quite a bit of typing required to refer to that list instance.

Alternative Way:- double brace initialization

Here is another way, making an anonymous inner class with an instance initializer (also known as a “double brace initialization”).

Simple Way:- Java 9 or later

List.of() the method was added to Java 9.

In Java 10 or later, after the var keyword was added:

This will give you an immutable List, so it cannot be changed.

Java 8 or earlier:

This will give you a List backed by the array, so it cannot change length.
But you can call List.set, so it’s still mutable.

Q: How to do The Java program to add elements to ArrayList in one line?

Answer: In Java 9 we can easily initialize an ArrayList in a single line:

But places are immutable (trying to change it will cause an UnsupportedOperationException exception to be thrown).

Example: adding new place

Error:-

java Initialization ArrayList in one line

Do comment if you have any doubts and questions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java Initialization of an ArrayList in one line codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.