Read only List, Map and Set in Java
Read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java, as shown in below example. Any modification in read only List will result in java.lang.UnSupportedOperationException in Java. This read-only List example is based on Java 5 generics but also applicable to other Java version like JDK 1.4 or JDK 1.3, just remove Generics code i.e. angle bracket which is not supported prior to Java 5. One common mistake programmer makes is that assuming fixed size List and read only List as same. As shown in our 3 example of converting Array to Array List , we can use Arrays.asList() method to create and initialized List at same line. List implementation returned by this method is fixed size and it doesn’t allow adding or removal of element but it is not read only because you can update objects by calling set(index) method. How to make a collection read only is also a popular Java collection interview question, which makes this Java collection tutorial even more important.