How to test if a List is an Unmodifable List in Java?

Java 8Object Oriented ProgrammingProgramming

We will first set a list to unmodifiable and after that test if it is unmodifiable or not. Let us create a List and add elements −

List <Integer> list = new LinkedList <Integer> ();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);

Set the above list to unmodifiable −

List<Integer>unmodifiable = Collections.unmodifiableList(list);

Now, use If-else, to check whether the list in unmodifiable or not −

if (unmodifiable.getClass().getName().contains("UnmodifiableList"))
   System.out.println("This is an UnmodifiableList" );
else
   System.out.println("This is not an UnmodifiableList" );

Example

 Live Demo

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<Integer>list = new LinkedList<Integer>();
      list.add(10);
      list.add(20);
      list.add(30);
      list.add(40);
      list.add(50);
      List<Integer>unmodifiable = Collections.unmodifiableList(list);
      if (unmodifiable.getClass().getName().contains("UnmodifiableList"))
         System.out.println("This is an UnmodifiableList" );
      else
         System.out.println("This is not an UnmodifiableList" );
   }
}

Output

This is an UnmodifiableList
raja
Published on 24-Apr-2019 10:35:57
Advertisements