Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I add multiple items to a Java ArrayList in single statement?
We can use Arrays.asList() method to add multiple items to a Java ArrayList in a single statement. This method returns a fixed-size list backed by the specified array, which we then pass to the ArrayList constructor to create a modifiable list.
Syntax
public static <T> List<T> asList(T... a)
Returns a fixed-size list backed by the specified array.
- T − The runtime type of the array.
- a − The array by which the list will be backed.
Note − The list returned by Arrays.asList() is fixed-size, meaning you cannot add or remove elements from it. To get a modifiable list, pass it to the ArrayList constructor.
Example
The following example shows how to create an ArrayList with multiple items in a single statement ?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
// Create a modifiable list with multiple items in one statement
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
System.out.println(list);
// Since it's an ArrayList, we can add more items
list.add("D");
System.out.println(list);
}
}
The output of the above code is ?
[A, B, C] [A, B, C, D]
Conclusion
Use new ArrayList<>(Arrays.asList(...)) to create a modifiable ArrayList with multiple items in a single statement. For Java 9+, you can also use List.of("A", "B", "C") for an immutable list, or wrap it in new ArrayList<>(List.of(...)) for a modifiable one.
