EN
Java - immutable ArrayList in Java
4 points
In this short article, we would like to how in Java create immutable List
- read-only list.
This technique can be used with all classes that implements List
interface
. Main advantage of this approach is: the list is only covered by class - list is not copied that makes solution very fast.
Quick solution:
xxxxxxxxxx
1
Collections.unmodifiableList(list);
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
import java.util.ArrayList;
4
import java.util.Collections;
5
6
public class Example {
7
8
public static void main(String[] args) {
9
10
List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three"));
11
List<String> immutableList = Collections.unmodifiableList(list);
12
13
immutableList.add("four");
14
}
15
}
Output:
xxxxxxxxxx
1
Exception in thread "main" java.lang.UnsupportedOperationException
2
at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1060)
3
at Example.main(Example.java:13)
Note: in read-only list we are not able to do any modification.