How to Initialize an ArrayList in One Line in Java

Avatar

By squashlabs, Last Updated: Nov. 3, 2023

How to Initialize an ArrayList in One Line in Java

There are several ways to initialize an ArrayList in one line in Java. Here are two possible approaches:

Approach 1: Using the Arrays.asList() method

You can use the Arrays.asList() method to initialize an ArrayList in one line. This method takes a variable number of arguments and returns a fixed-size List backed by the specified array. Here's an example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Initialize ArrayList in one line
        List fruits = new ArrayList(Arrays.asList("Apple", "Banana", "Orange"));

        // <a href="https://www.squash.io/how-to-print-arraylist-in-java/">Print the ArrayList</a>
        System.out.println(fruits);
    }
}

This will output:

[Apple, Banana, Orange]

In the above example, we create a new ArrayList and pass the result of Arrays.asList() as an argument to the ArrayList constructor. This initializes the ArrayList with the elements "Apple", "Banana", and "Orange" in one line.

Related Article: How To Fix Java Certification Path Error

Approach 2: Using Java 9's List.of() method

If you are using Java 9 or later, you can also use the List.of() method to initialize an ArrayList in one line. This method is a convenient way to create an immutable List with a fixed number of elements. Here's an example:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Initialize ArrayList in one line
        List fruits = new ArrayList(List.of("Apple", "Banana", "Orange"));

        // Print the ArrayList
        System.out.println(fruits);
    }
}

This will output:

[Apple, Banana, Orange]

In the above example, we create a new ArrayList and pass the result of List.of() as an argument to the ArrayList constructor. This initializes the ArrayList with the elements "Apple", "Banana", and "Orange" in one line.

Alternative ideas and suggestions

- If you don't want to use the ArrayList constructor, you can also initialize an ArrayList using the add() method. Here's an example:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Initialize ArrayList in one line
        List fruits = new ArrayList();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Print the ArrayList
        System.out.println(fruits);
    }
}

This will output:

[Apple, Banana, Orange]

- If you know the size of the ArrayList in advance, you can also specify the initial capacity when creating the ArrayList. This can help improve performance if you know the approximate number of elements the ArrayList will hold. Here's an example:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Initialize ArrayList with initial capacity
        List fruits = new ArrayList(3);
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Print the ArrayList
        System.out.println(fruits);
    }
}

This will output:

[Apple, Banana, Orange]

Best practices

- When initializing an ArrayList in one line, consider using the Arrays.asList() method if you need a mutable ArrayList or the List.of() method if you need an immutable ArrayList.

- If you are using an older version of Java that does not support List.of(), consider upgrading to a newer version to take advantage of the convenience it offers.

- If you know the size of the ArrayList in advance and performance is a concern, consider specifying the initial capacity when creating the ArrayList.

Tutorial: Best Practices for Java Singleton Design Pattern

This guide provides examples of best practices for the Java Singleton Design Pattern. Learn about lazy initialization, thread safety, serialization-s… read more

Java Comparable and Comparator Tutorial

The article provides a practical guide on how to use Comparable and Comparator in Java. With clear examples and best practices, this tutorial covers … read more

How to Generate Random Numbers in Java

Generating random numbers is a common task in Java programming. This article explores two approaches for generating random numbers using Java's java … read more

Java Adapter Design Pattern Tutorial

The Adapter Design Pattern in Java is a powerful tool that allows you to seamlessly connect incompatible classes and interfaces. In this tutorial, yo… read more

How to Use and Manipulate Arrays in Java

Learn how to use and manipulate Java String Arrays in this tutorial. Understand the basics and master array manipulation in Java. This article covers… read more

How to Set the JAVA_HOME in Linux for All Users

Setting JAVA_HOME in Linux for all users can be achieved through two different methods. The first method involves setting JAVA_HOME in the /etc/envir… read more

Java Design Patterns Tutorial

Software engineering has evolved rapidly over the years, bringing both positive changes and increased complexity. As software becomes more integral t… read more

Resolving MySQL Connection Issues in Java

Resolving MySQL connection issues in Java can be a challenging task, especially when it works perfectly in Workbench. This article provides solutions… read more

Java Hashmap Tutorial

This article provides a comprehensive guide on efficiently using Java Hashmap. It covers various use cases, best practices, real-world examples, perf… read more

How to Find the Max Value of an Integer in Java

This article provides a simple guide to finding the maximum integer value in Java. It covers various methods, including using the Integer.MAX_VALUE c… read more