Java ( Java 8, Java 11 ) : Example of Instantiating a List
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Vector;
class CreateList {
public List<String> array_list;
public List<Integer> linked_list;
public List<Boolean> vector;
CreateList() {
array_list = new ArrayList<String>();
linked_list = new LinkedList<Integer>();
vector = new Vector<Boolean>();
}
public void DisplayElements () {
System.out.println("Contents of ArrayList :");
for (String str : array_list) {
System.out.println(str);
}
System.out.println("Contents of LinkedList :");
for (Integer i : linked_list) {
System.out.println(i);
}
System.out.println("Contents of VectorList :");
for (Boolean b : vector) {
System.out.println(b);
}
}
public static void main (String[] args) {
CreateList obj = new CreateList();
obj.array_list.add("one");
obj.array_list.add("two");
obj.array_list.add("three");
obj.linked_list.add(12);
obj.linked_list.add(6);
obj.linked_list.add(24);
obj.vector.add(true);
obj.vector.add(false);
obj.vector.add(true);
obj.DisplayElements();
}
}
Output
Contents of ArrayList :
one
two
three
Contents of LinkedList :
12
6
24
Contents of VectorList :
true
false
true
Java ( Java 11 ) : Example of initializing a List
Note : Lists initialized using List.of and Arrays.asList are immutable i.e the content of lists thus created is constant. Any operation to add, delete or modify an immutable list will result in UnsupportedOperationException.
import java.util.List;
import java.util.Arrays;
class InitializeList {
public void DisplayElements (List<String> str_list, List<Integer> int_list) {
System.out.println("Contents of String List :");
for (String str : str_list) {
System.out.println(str);
}
System.out.println("Contents of Integer List :");
for (Integer i: int_list) {
System.out.println(i);
}
}
public static void main (String[] args) {
// Initialize list using List.of
List<String> string_list = List.of("one", "two", "three");
// Initialize list using Arrays.asList
List<Integer> int_list = Arrays.asList(1, 2, 3, 4);
InitializeList obj = new InitializeList();
obj.DisplayElements(string_list, int_list);
}
}
Output
Contents of String List :
one
two
three
Contents of Integer List :
1
2
3
4