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


Tip of the Day
Language: Java
Expertise: Intermediate
May 8, 2019

WEBINAR:

On-Demand

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


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

*/
M S Sridhar
 
Thanks for your registration, follow us on our social networks to keep up-to-date