Unmodifiable List in Java

In this post, we will discuss various methods to create 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. Arrays.asList()

Arrays.asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is not possible 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.

Java

Download   Run Code

Output:

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

2. Java Collections – Collections.unmodifiableList()

Collections unmodifiableList() 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 back in the unmodifiable list.

Java

Download   Run Code

Output:

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

3. Java Collections – Collections.unmodifiableCollection()

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.

Java

Download   Run Code

Output:

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

4. Apache Commons Collections – ListUtils.unmodifiableList()

Apache Commons Collections ListUtils class provides unmodifiableList() 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 modify operation is performed on it. However, any changes made to the original list will be reflected in the returned list.

Java

Download

Output:

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

 
Suggested Read: Immutable List in Java

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz