Skip to content

Best Way to Initialization ArrayList in one line | Java List

  • by

Actually, probably the “best” way to initialize the ArrayList is the method is not needed to create a new List in any way. There are many ways to do this because 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.

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

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”).

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

Simple Way:- Java 9 or later

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

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

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

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

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

Java 8 or earlier:

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

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 add elements to ArrayList in one line?

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

List places = List.of("Buenos Aires", "Córdoba", "La Plata");

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

Example: adding new place

import java.util.List;

public class Hello {


    public static void main(String[] arg){

        List places = List.of("Buenos Aires", "Córdoba", "La Plata");
        places.add("USA");
    }
    
}

Error:-

java Initialization ArrayList in one line

Do comment if you have any doubts or questions about 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading