How to make an ArrayList read only in Java
In Java, there are several ways to make an ArrayList read-only. Here are some of them:
- Using Collections.unmodifiableList() method:
We can use the
Collections.unmodifiableList()
method to create an unmodifiable view of the ArrayList. This method returns a read-only view of the original ArrayList, which means that any attempt to modify the list will result in an UnsupportedOperationException.
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
List<String> readOnlyList = Collections.unmodifiableList(list);
// Attempt to modify the read-only list
readOnlyList.add("grape"); // This will throw an UnsupportedOperationException
}
}
- Using the constructor of the ImmutableList class from the Guava library: The Guava library provides an ImmutableList class that can be used to create an immutable list. We can pass the ArrayList to the constructor of the ImmutableList class to create an immutable view of the list.
Example:
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
ImmutableList<String> immutableList = ImmutableList.copyOf(list);
// Attempt to modify the immutable list
immutableList.add("grape"); // This will throw an UnsupportedOperationException
}
}
- Using the constructor of the List.of() method: Since Java 9, we can use the List.of() method to create an immutable list. We can pass the elements of the ArrayList to the List.of() method to create an immutable view of the list.
Example:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
List<String> immutableList = List.of(list.toArray(new String[0]));
// Attempt to modify the immutable list
immutableList.add("grape"); // This will throw an UnsupportedOperationException
}
}