 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I add multiple items to a Java ArrayList in single statement?
We can utilize Arrays.asList() method to get a List of specified elements in a single statement.
Syntax
public static <T> List<T> asList(T... a)
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
Type Parameter
- T − The runtime type of the array. 
Parameters
- a − The array by which the list will be backed. 
Returns
A list view of the specified array
In case we use Arrays.asList() then we cannot add/remove elements from the list. So we use this list as an input to the ArrayList constructor to make sure that list is modifiable.
Example
The following example shows how to create a List with multiple items in a single statement.
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo {    public static void main(String[] args) { // Create a list object       List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));       // print the list       System.out.println(list); list.add("D");       System.out.println(list);    } }  Output
This will produce the following result −
[A, C, D] [A, B, C, D]
Advertisements
 