How to create a read-only list in Java?

Java 8Object Oriented ProgrammingProgramming

Let us first create a List in Java −

List<String>list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");

Now to convert the above list to read-only, use Collections −

list = Collections.unmodifiableList(list);

We have converted the above list to read-only. Now, if you will try to add more elements to the list, then the following error would be visible −

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

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<String>list = new ArrayList<String>();
      list.add("A");
      list.add("B");
      list.add("C");
      list = Collections.unmodifiableList(list);
      // An exception is thrown since its a read-only list now
      list.add("D");
      list.add("E");
      list.add("F");
      System.out.println(list);
   }
}

The output is as follows. Since it’s a read-only list, an error would be visible −

Output

Exception in thread "main" java.lang.Error:Unresolved compilation problem:
String literal is not properly closed by a double-quote
at Amit/my.Demo.main(Demo.java:18)
raja
Published on 24-Apr-2019 09:25:39
Advertisements