Initializing a List in Java
The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector, and Stack classes.
List is an interface, and the instances of List can be created in the following ways:
List a = new ArrayList();
List b = new LinkedList();
List c = new Vector();
List d = new Stack();
Examples:
filter_none
edit
play_arrow
brightness_4
import java.util.*;
import java.util.function.Supplier;
public class GFG {
public static void main(String args[])
{
// For ArrayList
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
System.out.println("ArrayList : " + list.toString());
// For LinkedList
List<Integer> llist = new LinkedList<Integer>();
llist.add(2);
llist.add(4);
System.out.println("LinkedList : " + llist.toString());
// For Stack
List<Integer> stack = new Stack<Integer>();
stack.add(3);
stack.add(1);
System.out.println("Stack : " + stack.toString());
}
} |
Output:
ArrayList : [1, 3]
LinkedList : [2, 4]
Stack : [3, 1]