Understanding the Collections.unmodifiableCollection

Collection has an unmodifiableCollection method that returns a collection object that cannot be modified. It means that you cannot add or remove any element from the collection.

import java.util.*;public class UnmodifiableCollection{   public static void main(String args[])   {      UnmodifiableCollection unmodifiableCollectionIns = new UnmodifiableCollection();      unmodifiableCollectionIns.proceed();   }      private void proceed()   {      List modifiableList = new ArrayList();      modifiableList.add("Java");      modifiableList.add("C++");      modifiableList.add(".Net");      modifiableList.add("Python");      System.out.println("Modifiable list: " + modifiableList);            Collection unmodifiableCollection = Collections.unmodifiableCollection(modifiableList);            System.out.println("Unmodifiable list: " + unmodifiableCollection);            System.out.println("Attempting to add new item to unmodifiableCollection...");      //This will thrown and exception since we are attempting to add to an unmodifiable collection      unmodifiableCollection.add("Perl");   }}/*

Expected output:

[[email protected]]# java UnmodifiableCollectionModifiable list: [Java, C++, .Net, Python]Unmodifiable list: [Java, C++, .Net, Python]Attempting to add new item to unmodifiableCollection...Exception in thread "main" java.lang.UnsupportedOperationException        at java.util.Collections$UnmodifiableCollection.add(Unknown Source)        at UnmodifiableCollection.proceed(UnmodifiableCollection.java:31)        at UnmodifiableCollection.main(UnmodifiableCollection.java:14)*/
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: