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:
Collections.unmodifiableList(list);
Practical example
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Example {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three"));
List<String> immutableList = Collections.unmodifiableList(list);
immutableList.add("four");
}
}
Output:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1060)
at Example.main(Example.java:13)
Note: in read-only list we are not able to do any modification.