Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 create a read-only list in Java?
Let us first create a List in Java −
List<String>list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
Now to convert the above list to read-only, use Collections −
list = Collections.unmodifiableList(list);
We have converted the above list to read-only. Now, if you will try to add more elements to the list, then the following error would be visible −
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Example
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
public static void main(String args[]) throws Exception {
List<String>list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list = Collections.unmodifiableList(list);
// An exception is thrown since its a read-only list now
list.add("D");
list.add("E");
list.add("F");
System.out.println(list);
}
}
The output is as follows. Since it’s a read-only list, an error would be visible −
Output
Exception in thread "main" java.lang.Error:Unresolved compilation problem: String literal is not properly closed by a double-quote at Amit/my.Demo.main(Demo.java:18)
Advertisements