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.
Read only List, Set and Map Example - Java
Here is sample Java program which demonstrate method of creating read only List, Set and Map in Java. You can make any List, Set or Map implementation as read only by following code example. Just remember that Collections.unModifiableList() , Collections.unModifiableSet() and Collections.unModifiableMap() method in Java. On read only List add, remove and set operation is not permitted, on read only Set you can not add or remove elements and in read only Map you can not put new entries or update existing entries. You can use same methods to convert any List implementation like ArrayList, LinkedList or Vector to read only ArrayList , LinkedList and Vector in Java.
That’s all on how to create read only List, Set and Map in Java. Its very easy to make any List implementation read only by wrapping it with Collections.unModifiableList(). Use same technique to convert any other Collection into read only in Java.
Other Java collection tutorial from Javarevisited