devxlogo

Understanding the Collections.unmodifiableCollection

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:

[root@mypc]# 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)*/
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist