- Trending Categories
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
Java Program to convert a list to a read-only list
Let’s say the following is our list which isn’t read-only:
List < Integer > list = new ArrayList < Integer > (); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); list.add(20); list.add(40); list.add(50);
Convert the above list to Read-only:
list = Collections.unmodifiableList(list);
On conversion, now you won’t be add or remove elements from the List. Let us see an example:
The following program will give an error because we first update the list to read only and then try to remove an element from it, which is not possible now. The reason is we have converted the list to readonly and you cannot add or remove element from a read-only list:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Demo { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); list.add(20); list.add(40); list.add(50); System.out.println("List = "+list); // converting to read-only list = Collections.unmodifiableList(list); list.remove(5); System.out.println("Updated List: "+list); } }
The following is the output with an error since we are removing an element from a read-only list:
List = [10, 20, 30, 40, 50, 20, 40, 50] Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.Collections$UnmodifiableList.remove(Collections.java:1316) at Amit/my.Demo.main(Demo.java:27)
- Related Articles
- How to create a read-only list in Java?
- Java Program to convert a Map to a read only map
- Java Program to convert a List to a Set
- Java program to convert a list to an array
- Java program to convert an array to a list
- Program to convert a Vector to List in Java
- Java Program to convert Properties list into a Map
- Java Program to convert Stream to List
- Java program to convert a list of characters into a string
- Java program to convert the contents of a Map to list
- How to convert an Array to a List in Java Program?
- Program to convert List to Stream in Java
- Program to convert Set to List in Java
- Program to convert Array to List in Java
- Program to convert List of Integer to List of String in Java

Advertisements