You can create a read-only Collection by using unmodifiableCollection() method, which returns you a unmodifiable or a read only collection. It will not allow you to add or remove element from the collection. When we try to modify the collection it will throw the java.lang.UnsupportedOperationException. Here we will try to make the Collection, List, Set and Map read-only.
We will use the unmodifiableCollection(),unmodifiableList(),unmodifiableSet(),UnmodifiableMap() methods of the Collections class to achieve it .Lets see the below code.
package com.javainterviewpoint; import java.util.ArrayList; import java.util.Collection; 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 UnModifiableCollection { public static void main(String args[]) { List tempList = new ArrayList(); tempList.add("Java"); tempList.add("InterviewPoint"); System.out.println("UnModified List :"+tempList); //Creating a read only collection Collection readOnlyCollection = Collections.unmodifiableCollection(tempList); //add to the readOnlyCollection is not supported, throws java.lang.UnsupportedOperationException readOnlyCollection.add("Java InterviewPoint"); //Make the list readonly List readOnlyList = Collections.unmodifiableList(tempList); //add will throw exception readOnlyList.add("Test"); //remove operation is also not supported readOnlyList.remove("InterviewPoint"); Set readOnlySet = new HashSet(tempList); System.out.println("Unmodified Set :"+readOnlySet); //Set has been changed to readOnly readOnlySet = Collections.unmodifiableSet(readOnlySet); //Both add and remove is not supported,will throw exception readOnlySet.add("ReadOnlySet"); readOnlySet.remove("Java"); Map tempMap = new HashMap(); tempMap.put("IN","India"); tempMap.put("US", "US"); //Making the map to readonly Map readOnlyMap = Collections.unmodifiableMap(tempMap); //Both add and remove is not supported,will throw exception readOnlyMap.put("UK","England"); readOnlyMap.remove("UK"); } }
When we try to run the code with modification, it will throw UnsupporetedOperationException
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Unknown Source) at com.javainterviewpoint.UnModifiableCollection.main(UnModifiableCollection.java:25)
Leave a Reply