How to initialize a list with values in Java
In this tutorial, we are going to see how to initialize a List with values in Java. Java.util.List is a child interface of the Collection interface. This is a collection of ordered objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and the insertion of elements. List interface is implemented by ArrayList, LinkedList, Vector, and Stack classes.
[st_adsense]
List is an interface and List instances can be created in the following ways:
List arrayList = new ArrayList(); List linkedList = new LinkedList(); List vector = new Vector(); List stack = new Stack();
Here are the different ways to initialize a list:
Using List.add() method
List is an interface, we cannot instantiate it directly. However, we can create objects of those classes which implemented this interface and instantiate them.
The classes that implement the List interface are ArrayList, LinkedList, Vector, Stack etc.
Example :
import java.util.*; public class Main { public static void main(String args[]) { //ArrayList List<String> list1 = new ArrayList<String>(); list1.add("A"); list1.add("B"); list1.add("C"); System.out.println("ArrayList : " + list1); //LinkedList List<String> list2 = new LinkedList<String>(); list2.add("A"); list2.add("B"); list2.add("C"); System.out.println("LinkedList : " + list2); //Stack List<String> list3 = new Stack<String>(); list3.add("A"); list3.add("B"); list3.add("C"); System.out.println("Stack : " + list3); } }
Output:
ArrayList : [A, B, C] LinkedList : [A, B, C] Stack : [A, B, C][st_adsense]
Using Arrays.asList() method
Arrays.asList() creates an immutable list from an array. Therefore, it can be used to instantiate a list with an array.
Syntax:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Example:
import java.util.*; public class Main { public static void main(String args[]) { // Instantiating the list using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3, 4); // Print the list System.out.println(list.toString()); } }
Output:
[1, 2, 3, 4][st_adsense]
How to create an editable list in Java:
import java.util.*; public class Main { public static void main(String args[]) { // Instantiating the list List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4)); // Print the list before adding the value System.out.println(list.toString()); list.add(5); // Print the list after adding the value System.out.println(list.toString()); } }
Output:
[1, 2, 3, 4] [1, 2, 3, 4, 5][st_adsense]