Home » Tip Bank » Java
  • Comment on this Article
Language: Java
Expertise: Intermediate
May 8, 2019
  • facebook
  • twitter
  • in
  • Email

WEBINAR:

On-Demand

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


Watch

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
 
Submit a Tip
Browse "Java" Tips
Browse All Tips
googlecode.com
javascriptkit.com