- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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)
- Related Articles
- Create a Read-Only Collection in Java
- Java Program to convert a list to a read-only list
- Create a file and change its attribute to read-only in Java
- Java Program to create a file and sets it to read-only
- How to make a collection read only in java?
- How to make Java ArrayList read only?
- How to make an ArrayList read only in Java?
- Make a Hashtable read-only in Java
- Change a file attribute to read only in Java
- How to create a List Spinner in Java?
- Java Program to convert a Map to a read only map
- Mark file or directory Read Only in Java
- How to add read-only property in C#?
- How do you create a list in Java?
- How to list all files (only) from a directory using Java?

Advertisements