Question
How can I create a read-only ArrayList in Java that prevents any modifications after it is initialized?
List<String> readOnlyList = Collections.unmodifiableList(new ArrayList<>(Arrays.asList("Element1", "Element2", "Element3")));
Answer
In Java, to create a read-only ArrayList, you can utilize the `Collections.unmodifiableList()` method that ensures the list cannot be modified after initialization. This approach is beneficial when you want to provide a stable API without risks of unintended modifications.
import java.util.*;
public class ReadOnlyArrayListExample {
public static void main(String[] args) {
List<String> originalList = new ArrayList<>(Arrays.asList("Element1", "Element2", "Element3"));
List<String> readOnlyList = Collections.unmodifiableList(originalList);
System.out.println(readOnlyList); // Output: [Element1, Element2, Element3]
// The following line will throw UnsupportedOperationException:
// readOnlyList.add("Element4");
}
}
Causes
- Modifying an ArrayList can lead to data inconsistencies in your application.
- You may want to expose data without allowing modifications.
Solutions
- Use `Collections.unmodifiableList()` to create a read-only version of an ArrayList.
- Create an immutable list using `List.of()` in Java 9 and later, which inherently does not allow any modifications.
Common Mistakes
Mistake: Using a modifiable ArrayList instead of creating a wrapped unmodifiable list.
Solution: Wrap the ArrayList with `Collections.unmodifiableList()` before exposing it.
Mistake: Not handling UnsupportedOperationException when modifying a read-only list.
Solution: Always be cautious of the exception and avoid operations that change the list.
Helpers
- Java read-only ArrayList
- unmodifiable ArrayList Java
- convert ArrayList to read-only
- Java prevent ArrayList modification