1.

How can you make an ArrayList read-only in Java?

Answer»

With the help of Collections.unmodifiableList() method, we can easily make an ArrayList read-only.  This function takes a CHANGEABLE ArrayList as an input and returns the ArrayList's read-only, unmodified view.

Example:

import java.util.*; public class InterviewBit { public static void MAIN(String[] args) throws Exception { try { // creating object of ArrayList<String> LIST<String> sample_list = new ArrayList<String>(); sample_list.add(“practice”); sample_list.add(“SOLVE”); sample_list.add(“interview”); // DISPLAYING the initial list System.out.println("The initial list is : " + sample_list); // using unmodifiableList() method List<String> read_only_list = Collections .unmodifiableList(sample_list); // displaying the read-only list System.out.println("The ReadOnly ArrayList is : " + read_only_list); // Trying to add an element to the read-only list System.out.println("Trying to modify the ReadOnly ArrayList."); read_only_list.add(“job”); } catch (UnsupportedOperationException e) { System.out.println("The exception thrown is : " + e); } }}

Output:

The initial list is : [practice, solve, interview]The ReadOnly ArrayList is : [practice, solve, interview]Trying to modify th eReadOnly ArrayList.Exception thrown : java.lang.UnsupportedOperationException

We can see that as we try to add an element to a read-only ArrayList we get an exception thrown.



Discussion

No Comment Found