java.util.Collections.unmodifiableList() Method


Advertisements


Description

The unmodifiableList() method is used to returns an unmodifiable view of the specified list.

Declaration

Following is the declaration for java.util.Collections.unmodifiableList() method.

public static <T> List<T> unmodifiableList(List<? extends T> list)

Parameters

list − This is the list for which an unmodifiable view is to be returned.

Return Value

  • The method call returns an unmodifiable view of the specified list.

Exception

NA

Example

The following example shows the usage of java.util.Collections.unmodifiableList()

Live Demo
package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String[] args) {
      
      // create array list
      List<Character> list = new ArrayList<Character>();

      // populate the list
      list.add('X');
      list.add('Y');

      System.out.println("Initial list: "+ list);

      // make the list unmodifiable
      List<Character> immutablelist = Collections.unmodifiableList(list);

      // try to modify the list
      immutablelist.add('Z');      
   }
}

Let us compile and run the above program, this will produce the following result.

Initial list: [X, Y]
Exception in thread "main" java.lang.UnsupportedOperationException

java_util_collections.htm

Advertisements