Menu
Topics Index
...
`

ReadOnlyCollectionsDemo - Java Example Program


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

class ReadOnlyCollectionsDemo
{
    public static void main(String arg[])
    {
        List array = Arrays.asList(new String[] { "Rama", "Seetha", "Lakshman" }); //LINE A
        List list = new ArrayList(array); // LINE B
        List unmodifiableList = Collections.unmodifiableList(list); //LINE C
        
        Map hm = new HashMap(); // LINE D
        hm.put("Geetha", "Seetha");
        hm.put("Bharath", "Lakshman");
        Map unmodifiableMap = Collections.unmodifiableMap(hm);
        
        try
        {
            unmodifiableMap.put("Radha", "Rani");// LINE E
        }
        catch(UnsupportedOperationException e)
        {
            System.out.println("We cannot modify a read only collection.");
        }
    
    }
}
OUTPUT

We cannot modify a read only collection.

DESCRIPTION

At LINE A we created a list.At LINE B, LINE C we make a list as read only. At LINE D we created a hash map, make it as read only and modified. At LINE E, we are modifying the hash map and we are checking that it throws an UnsupportedOperationException since it is read only.

THINGS TO TRY
  • Place the below shown code after LINE C and observe the output. It should throw an exception.
    unmodifiableList.add("Ramani");

© meritcampus 2019

All Rights Reserved.

Open In App