How to make Java ArrayList read only?

Java 8Object Oriented ProgrammingProgramming

You can make a collection unmodifiable using the unmodifiableList() method of the Collections interface.

Example

Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Sample {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println(list);
      List myList= (List) Collections.unmodifiableList(list);
      myList.add("Apache Hadoop");
      System.out.println(myList);
   }
}

Output

Exception in thread "main" [JavaFx, Java, WebGL, OpenCV]
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at collections_package.Sample.main(Sample.java:16)
raja
Published on 17-Jan-2018 05:58:03
Advertisements