This post will discuss various methods to create an unmodifiable list in Java.

Unmodifiable lists are “read-only” wrappers over other collections. They do not support any modification operations such as add, remove, and clear, but their underlying collection can be changed. Lists that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.

It is worth noting that making a list final will not make it Unmodifiable. We can still add elements or remove elements from it. Only the reference to the list is final.

1. Using Arrays.asList() method

Arrays.asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it. The list will throw an UnsupportedOperationException if any resize operation is performed on it.

However, the list can be modified if:

  1. set(int index, E element) is called on the list which will replace the element at the specified index in this list with the specified element.
  2. Any change is made to the original array which will be reflected back in the returned list.

The following program demonstrates it:

Download  Run Code

Output:

java.lang.UnsupportedOperationException
List : [C, C++, Java]
Array : [C, Go, JS]

2. Using Collections.unmodifiableList() method

Collections unmodifiableList() method returns an unmodifiable “read-only” view of the specified list. Any attempt to modify the returned list directly or via its iterator will result in an UnsupportedOperationException. However, any changes made to the original list will be reflected in the unmodifiable list.

Download  Run Code

Output:

java.lang.UnsupportedOperationException
[C, C++, Java, Go]

3. Using Collections.unmodifiableCollection() method

Collection interface offers another method, unmodifiableCollection(), which returns an unmodifiable view of the specified collection. This is similar to unmodifiableList() except it returns a Collection instead of a List.

Download  Run Code

Output:

java.lang.UnsupportedOperationException
[C, C++, Java, Go]

4. Using Apache Commons Collections

Apache Commons Collections ListUtils class provides unmodifiableList() method that returns an unmodifiable list backed by the given list. If the given list is null, it throws a NullPointerException. The list will throw an UnsupportedOperationException if any modification operation is performed on it. However, any changes made to the original list will be reflected in the returned list.

Download Code

Output:

java.lang.UnsupportedOperationException
[C, Go, Perl]

That’s all about unmodifiable List in Java.

 
Suggested Read:

Immutable List in Java