Topics Index

Collections Framework > Collection Algorithms >
Siva Nookala - 20 Feb 2017
We can create Read only Collections by using Collections.unmodifiableCollection() utility method. It returns unmodifiable or read only view of Collection in which you can not perform any operation that will change the collection like add, remove and set either directly or while iterating over iterator. It raises UnsupportedOperationException whenever you try to modify the List. If the list is read-only then you can not add or change any element of the list. We usually use this when we want to pass the collection, but does not want to the user to accidentally modify it.

Read only collection can also be called as unmodifiable or Immutable collection in Java.

The following methods make a Collection read only.
  • Collections.unmodifiableList
  • Collections.unmodifiableSet
  • Collections.unmodifiableMap
  • Collections.unmodifiableSortedMap
  • Collections.unmodifiableSortedSet
These methods takes collection parameter and return a new read-only collection with same elements as in original collection.
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);
            unmodifiableMap.put("Radha", "Rani");// LINE E
        catch(UnsupportedOperationException e)
            System.out.println("We cannot modify a read only collection.");

We cannot modify a read only collection.


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.

  • Place the below shown code after LINE C and observe the output. It should throw an exception.
We can also create read only ArrayList by using Arrays.asList(String[]{}).

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App