Create and demonstrate an immutable collection in Java


In order to create and demonstrate an immutable collection in Java, we use the unmodifiableCollection() method. This method returns an unmodifiable and immutable view of the collection.

Declaration − The java.util.Collections.unmodifiableCollection() method is declared as follows -

public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)

where c is the collection whose immutable view is to returned.

Let us see a program to create and demonstrate an immutable collection in Java −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(10);
      list.add(50);
      list.add(30);
      list.add(20);
      list.add(40);
      list.add(60);
      System.out.println("Original list : " + list);
      Collection<Integer> col = Collections.unmodifiableCollection(list);
      col.add(30);
      System.out.println(col);
   }
}

Since we try to add an element to an immutable collection, the program throws the following exception −

Output

Original list : [10, 50, 30, 20, 40, 60]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
at Example.main(Example.java:17)

Updated on: 29-Jun-2020

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements