dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Understanding the Collections.unmodifiableCollection

Learn how to use the unmodifiableCollection method in Java.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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 UnmodifiableCollection
Modifiable 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)

*/

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date