![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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)
Advertisements