In Java, there are useful methods to make a Collection class read
Only. We can make the Collection read Only by using one of the
following methods:
Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
Collections.unmodifiableCollection(Collection c)
xxxxxxxxxx
class GFG {
public static void main(String[] args)
{
// Set of Integer
Set<Integer> numbers = new HashSet<Integer>();
// Set have 1 to 10 numbers
for (int i = 1; i <= 5; i++) {
numbers.add(i);
}
// print the integers
numbers.stream().forEach(System.out::print);
// Removing element from the list
numbers.remove(5);
System.out.println("\nAfter Performing Operation");
numbers.stream().forEach(System.out::print);
System.out.println(
"\nSet is also By Default Readable and Writable");
// Now making Read-Only Set
// Using unmodifiableSet() method.
try {
numbers = Collections.unmodifiableSet(numbers);
// This line will generate an Exception
numbers.remove(4);
}
catch (UnsupportedOperationException
unsupportedOperationException) {
System.out.println(
"Exceptions is "
+ unsupportedOperationException);
}
finally {
System.out.println(numbers.contains(3));
System.out.println("Now Set is Read-Only");
}
}
}