Java Collection How to - Create a read-only list, via the unmodifiableList() method of the Collections class








Question

We would like to know how to create a read-only list, via the unmodifiableList() method of the Collections class.

Answer

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//www. j  ava 2  s.  c  om
public class MainClass {
  public static void main(String args[]) throws Exception {

    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    list = Collections.unmodifiableList(list);
    list.add(1, "G");

    System.out.println(list);

  }
}

The code above generates the following result.