How to make a List,Map,Set readonly in java

We can make any List,Set,Map as read only by using unModifiableList(),unModifiableSet(),unModifiableMap() methods available in Collections class.here is sample code

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ReadOnlyExample {
 
    public static void main(String args[]) {            
       
// creating a List
List list = new ArrayList();

//adding elements in list
list.add("a");
list.add("b");
list.add("c");
list.add("d"); 
 
System.err.println("before making list readonly : " + list);
 
//making list readonly using Collections.unmodifiableList() method
list = Collections.unmodifiableList(list);
 
//will throw java.lang.UnsupportedOperationException  no modification is allowed in a read only list
list.add("e");

//will throw java.lang.UnsupportedOperationException remove is not allowed in a read only list
list.remove("b");
 

  
    
  
    
//creating a Set using a list
Set set = new HashSet(list);
 
set.add("e");

System.out.println(" before making set read only " + set);
 
//making Set readonly  
set = Collections.unmodifiableSet(set);
 
//trying to add element in read only Set - java.lang.UnSupportedOperationException
set.add("f");
 
//trying to remove element from read only set
set.remove("a"); //you can not remove elements from read only Set
 
 
 
   // creating a hashmap 
 
Map<String, String> map = new HashMap<String, String>();      
map.put("a", "a");
map.put("b", "b"); 
 
System.out.println(" before making map read only" + map);
 
//making the Map read only 
map = Collections.unmodifiableMap(map);
   
//will throw java.lang.UnSupportedOperation no new entry can be added to a read only map
map.put("c", "c"); 
   
//  will throw java.lang.UnSupportedOperation we can not remove an element from map as it is in read only mode
map.remove("b"); 
 
    }
 
}





Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s