Create a Read-Only Collection in Java

Java 8Object Oriented ProgrammingProgramming

An example of a read-only collection can be an unmodifiable ArrayList. 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.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List aList = new ArrayList();
      aList.add("Apple");
      aList.add("Mango");
      aList.add("Guava");
      aList.add("Orange");
      aList.add("Peach");
      aList = Collections.unmodifiableList(aList);
      System.out.println("The ArrayList elements are: " + aList);
   }
}

The output of the above program is as follows −

The ArrayList elements are: [Apple, Mango, Guava, Orange, Peach]

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("Apple");
aList.add("Mango");
aList.add("Guava");
aList.add("Orange");
aList.add("Peach");
aList = Collections.unmodifiableList(aList);
System.out.println("The ArrayList elements are: " + aList);
raja
Published on 07-Feb-2019 13:12:25
Advertisements