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);
        godMap.put("mname", "kumar");  //Modifying after making unmodifiable
{lname=modi, fname=Deepak}
Exception in thread "Main Thread" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableMap.put(
    at Unmodifiable.main(


No comments:

Post a Comment