Java List.of and ArrayList.add
List.of creates a fixed, unmodifiable list of items. Copy it into an ArrayList when the shopper needs to add another item.
A simple example
List.of and ArrayList.add
- Start with List containing A
- Do this Append B
- Result A, B
Syntax
var basket = new ArrayList<>(List.of("Milk", "Rice"));
basket.add("Tea");
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaKeep the template and edit a copy
A preview changes one position in a badge or label while a master copy is still needed. Work out which value is mutable so editing the preview cannot alter the source used for the next print.
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
var usual = List.of("Milk", "Rice");
var basket = new ArrayList<>(usual);
basket.add("Tea");
System.out.println(usual);
System.out.println(basket);
}
}
[Milk, Rice] [Milk, Rice, Tea]
The template still has two items. The new basket starts with those items and grows independently.
Add the last student to the bus register
Two families have already booked seats on a school bus. A third student registers at the desk, so the coordinator appends the name and checks the final passenger count before departure.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var riders = new ArrayList<>(List.of("Mira", "Sam"));
riders.add("Nia");
System.out.println(riders.size());
}
}
3
The mutable register keeps the first two names and gains a third passenger.
Extend a reading list
A class has chosen one novel and adds two more titles. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.
What to watch for
Calling add on the list returned by List.of throws UnsupportedOperationException. Create a mutable copy before changing the basket.