We can use the Arrays.asList() method to get a list of specified elements in a single statement.
public static <T> List<T> asList(T... a)
Returns a fixed-size list backed by the specified array. (Changing the returned list "writes" the array.)
T − The runtime type of the array.
a - Array that supports lists.
In case we use Arrays.asList() then we cannot add/remove from the list element. Therefore, we use this list as input to the ArrayList constructor to ensure that the list is modifiable.
Example
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<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3)); // print the list System.out.println(list); list.add(4); System.out.println(list); } }
Output
[1, 2, 3] [1, 2, 3, 4]
The above is the detailed content of How to create a list with values in Java?. For more information, please follow other related articles on the PHP Chinese website!