Read Only Set in Java

In this example, We will show you how to make read only set in java. The example was tested and output has been shared in the post.

Example Program

package com.dineshkrish;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
/**
* 
* @author Dinesh Krishnan
*
*/
public class ReadOnlySet {
public static void main(String[] args) {
// defining set object
Set<String> set = new TreeSet<String>();
// adding the elements to set
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("E");
// making read only set
set = Collections.unmodifiableSet(set);
// trying to update set obejct
set.add("F");
System.out.println(set);
}
}

Run it

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

References

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

No responses yet

Leave a Reply

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