How to create a list
Short answer
A modifiable list is an ArrayList. You can add and remove elements:
void main() {
List<String> names = new ArrayList<>();
names.add("Anna");
names.add("Oleg");
IO.println(names);
IO.println(names.size());
}Output:
[Anna, Oleg]
2With elements right away
List.of() creates an unmodifiable list — handy for constants and read-only data:
void main() {
List<String> days = List.of("Mon", "Tue", "Wed");
IO.println(days.get(1));
}Output:
TueModifiable with initial elements
Pass List.of() to the ArrayList constructor — you get a modifiable copy:
void main() {
List<Integer> numbers = new ArrayList<>(List.of(3, 1, 2));
numbers.add(4);
numbers.remove(Integer.valueOf(1));
IO.println(numbers);
}Output:
[3, 2, 4]The type with var
With var the type is written only on the right:
void main() {
var prices = new ArrayList<Double>();
prices.add(9.99);
IO.println(prices);
}Output:
[9.99]Common mistake
Modifying a list from List.of(). It is unmodifiable, and any attempt throws:
void main() {
List<String> days = List.of("Mon", "Tue");
days.add("Wed");
}Output:
Exception in thread "main" java.lang.UnsupportedOperationExceptionAnother detail: List.of() does not accept null elements.
Functions used in this recipe
- List.of() — Creates an unmodifiable list from the listed elements.
- List.add() — Adds an element to the end of a list or at a given position.
- Collections.unmodifiableList() — Returns a view of a list that cannot be modified.
- Arrays.asList() — Returns a fixed-size list backed by an array.