Read Only Collection in Java

In this example, We will show you how to make read only collection in Java.

Example Program

package com.dineshkrish;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* 
* @author Dinesh Krishnan
*
*/
public class ReadOnlyCollection {
public static void main(String[] args) {
// defining collection object
Collection<String> collection = new ArrayList<String>();
// adding elements to collection
collection.add("A");
collection.add("B");
collection.add("C");
collection.add("D");
collection.add("E");
// making collection read only 
collection = Collections.unmodifiableCollection(collection);
// trying to do update or add
collection.add("F");
}
}

Run it

[su_highlight]Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at com.dineshkrish.ReadOnlyCollection.main(ReadOnlyCollection.java:31)
[/su_highlight]

References

1. Java List Interface
2. Java ArrayList Class
3. Java Collections Class
4. Java Collections.unmodifiableCollection() Method

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *