Get the unmodifiable view of the specified ArrayList in Java


The unmodifiable view of the specified ArrayList can be obtained by using the method java.util.Collections.unmodifiableList(). This method has a single parameter i.e. the ArrayList and it returns the unmodifiable view of that ArrayList.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List aList = new ArrayList();
      aList.add("Sally");
      aList.add("George");
      aList.add("John");
      aList.add("Susan");
      aList.add("Martha");
      aList = Collections.unmodifiableList(aList);
      System.out.println("The ArrayList elements are: " + aList);
   }
}

Output

The output of the above program is as follows

The ArrayList elements are: [Sally, George, John, Susan, Martha]

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The Collections.unmodifiableList()method is used to obtain the unmodifiable view of the ArrayList. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows

List aList = new ArrayList();
aList.add("Sally");
aList.add("George");
aList.add("John");
aList.add("Susan");
aList.add("Martha");
aList = Collections.unmodifiableList(aList);
System.out.println("The ArrayList elements are: " + aList);

Updated on: 29-Jun-2020

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements