- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to test if a List is an Unmodifable List in Java?
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
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
Advertisements
To Continue Learning Please Login
Login with Google