Thursday, March 1, 2012

Unmodifiable Collections in Java

The Collections class provides six factory methods, one for each of Collection:
List, Collection, Map, Set, SortedMap, and SortedSet.

    List unmodifiableList(List list)
    Collection unmodifiableCollection(Collection collection)
    Map unmodifiableMap(Map map)
    Set unmodifiableSet(Set set)
    SortedMap unmodifiableSortedMap(SortedMap map)
    SortedSet unmodifiableSortedSet(SortedSet set)

You should set the collection with required values then pass it as value to the Collections 
respective method. These methods will return you collection as read only. 

If you attempt to modify a read-only collection it will throw an UnsupportedOperationException.
====================
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Unmodifiable {
    public static void main(String[] args) {
        Map godMap = new HashMap();
        godMap.put("fname", "Deepak");
        godMap.put("lname", "modi");

        godMap = Collections.unmodifiableMap(godMap);
        System.out.println(godMap);
        
        godMap.put("mname", "kumar");  //Modifying after making unmodifiable
        System.out.println(godMap);
    }
}
//Output:
{lname=modi, fname=Deepak}
Exception in thread "Main Thread" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableMap.put(Collections.java:1286)
    at Unmodifiable.main(Unmodifiable.java:14)

====================END============

No comments:

Post a Comment