Java Collections unmodifiableList() Method
Example
Try to add an item to a read-only list:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
List<String> readOnly = Collections.unmodifiableList(cars);
try {
readOnly.add("BMW");
} catch (UnsupportedOperationException e) {
System.out.println("Error: the list cannot be changed.");
}
}
}
Definition and Usage
The unmodifiableList() method returns an unmodifiable (read-only) view of a list. You can read the items, but you cannot add, remove or change them. If you try, Java throws an UnsupportedOperationException.
The view is not a copy. If the original list changes, the view shows the change.
Syntax
public static List<T> unmodifiableList(List<T> list)
T refers to the data type of items in the list.
Parameter Values
| Parameter | Description |
|---|---|
| list | Required. The list to make a read-only view of. |
Technical Details
| Returns: | A read-only List that shows the items of the original list. |
|---|
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods