Showing posts with label Java collections. Show all posts
Showing posts with label Java collections. Show all posts

Thursday 16 April 2015

How to create a read-only collection in java?

Collections is one of the most used feature in Java/J2EE applications . 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.



 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 public class ReadOnlyCollections {  
           public static void main(String[] args) {  
                List<String> myList = new ArrayList<>();  
                myList.add("1");  
                myList.add("2");  
                myList.add("3");  
                System.out.println(myList);  
                // Convert to unmodifiable .  
                myList = Collections.unmodifiableList(myList);  
                myList.add("4");  
                System.out.println(myList);  
           }  
 }  
 Output -   
 [1, 2, 3]  
 Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.Collections$UnmodifiableCollection.add(Unknown Source)  
      at ReadOnlyCollections.main(ReadOnlyCollections.java:15)