Java Programing laungage

java.util Projects

java.util Project 1

Creating a Read-Only Collection

In This programming tutorials, we are going to make a collection read-only. In this page of tutorials, list has been represented for making it read-only. By default, list is not read-only. If the list is read-only then you can not add or change any element of the list.

Previous Home Next
adplus-dvertising

In the given program, we can see that a list has been made read-only using the unmodifiableList() method of the Collections class. If we want to do the same task for another collection like Collection, Set, SortedSet we have to use this methods.


Collection<T> unmodifiableCollection(Collection<? extends T> c)
List<T> unmodifiableList(List<? extends T> list)
Set<T> unmodifiableSet(Set<? extends T> s)
SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)

After making the collections read-only any attempts for the modification occurs then the errors are captured by the UnsupportedOperationException in the catch block.

Example


package r4r;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class readonlycollectiontest {
public static void main(String[] args) throws IOException{
 int n = 0;
 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
 System.out.print("How many String you want to enter in list : ");
 try{
 n = Integer.parseInt(in.readLine());
 }
 catch(NumberFormatException ne){
 System.out.println(ne.getMessage() + " is not right value.");
 System.out.println("Enter a numeric value only.");
 System.exit(1);
 }[an error occurred while processing this directive]
 String[] string = new String[n];
 System.out.println("Enter String for the list : ");
 for(int i = 0; i < n; i++){
	 string[i] = in.readLine();
 }
 List<String> lst = Arrays.asList(string);
 System.out.println("Available element are : " + lst);
 lst = Collections.unmodifiableList(lst);
 try{
 System.out.print("Entry for set to the list : ");
 lst.set(0, in.readLine());
 }
 catch(UnsupportedOperationException ue){
 System.out.println("Sorry, You can not modify the list.");
 System.exit(1);
 }
 }
}

Previous Home Next