Java 25 (LTS) reference · List and ArrayList Methods
Java List.of() Method
Create an immutable list from values. Adding or removing later throws UnsupportedOperationException.
Java 25 (LTS) Since Java 9
Syntax
List.of(e1, e2, ...)
Parameters
| Parameter | Description |
|---|---|
elementsE... |
The values (no nulls). |
Return value
An unmodifiable List<E>.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> days = List.of("Mon", "Tue", "Wed");
System.out.println(days + " size " + days.size());
try {
days.add("Thu");
} catch (UnsupportedOperationException e) {
System.out.println("List.of lists are immutable");
}
}
}
Output
[Mon, Tue, Wed] size 3 List.of lists are immutable
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> fixed = List.of(3, 1, 2);
List<Integer> copy = new ArrayList<>(fixed); // a mutable copy
copy.add(4);
System.out.println(copy);
}
}
Output
[3, 1, 2, 4]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 9 | Added |
Related
list.add()· Append an element to the end of a list, or insert it at an index, shifting later elements right.Map.of()· Create an immutable map from key-value pairs (up to 10 pairs; Map.ofEntries() for more). No null keys or values.- Java ArrayList · tutorial