List Interface
Key Characteristics
Elements keep the order they were inserted in
Duplicate values are allowed — the same value can appear at multiple indices
Every element has a numeric position, starting at index 0
Elements can be inserted, retrieved, updated, or removed by that index
Main Implementations
Declaring by interface, choosing an implementation
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // duplicates are allowed
System.out.println(fruits);
System.out.println(fruits.get(0));
System.out.println(fruits.size());
}
}[Apple, Banana, Apple] Apple 3
Common List Methods
Method | Purpose |
add(element) | Appends an element to the end of the list |
get(index) | Returns the element at the given index |
set(index, element) | Replaces the element at the given index |
remove(index) | Removes the element at the given index |
indexOf(element) | Returns the first index of an element, or -1 if absent |
contains(element) | Returns true if the element exists anywhere in the list |
size() | Returns the number of elements currently in the list |
Common List methods in action
import java.util.List;
import java.util.ArrayList;
public class ListMethodsDemo {
public static void main(String[] args) {
List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.set(1, "Yellow");
System.out.println(colors);
System.out.println(colors.indexOf("Blue"));
System.out.println(colors.contains("Purple"));
colors.remove(0);
System.out.println(colors);
}
}[Red, Yellow, Blue] 2 false [Yellow, Blue]
List.of() — Quick Immutable Lists (Java 9+)
List.of()
import java.util.List;
public class ImmutableListDemo {
public static void main(String[] args) {
List<String> days = List.of("Mon", "Tue", "Wed");
System.out.println(days);
days.add("Thu"); // throws UnsupportedOperationException
}
}[Mon, Tue, Wed]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)