
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Create a Read-Only Collection in Java
An example of a read-only collection can be an unmodifiable ArrayList. The unmodifiable view of the specified ArrayList can be obtained by using the method java.util.Collections.unmodifiableList(). This method has a single parameter i.e. the ArrayList and it returns the unmodifiable view of that ArrayList.
A program that demonstrates this is given as follows −
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 aList = new ArrayList(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); aList = Collections.unmodifiableList(aList); System.out.println("The ArrayList elements are: " + aList); } }
The output of the above program is as follows −
The ArrayList elements are: [Apple, Mango, Guava, Orange, Peach]
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The Collections.unmodifiableList()method is used to obtain the unmodifiable view of the ArrayList. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows −
List aList = new ArrayList(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); aList = Collections.unmodifiableList(aList); System.out.println("The ArrayList elements are: " + aList);
- Related Questions & Answers
- How to make a collection read only in java?
- How to create a read-only list in Java?
- Check if OrderedDictionary collection is read-only in C#
- Make a Hashtable read-only in Java
- Create a file and change its attribute to read-only in Java
- Java Program to create a file and sets it to read-only
- Change a file attribute to read only in Java
- How to make Java ArrayList read only?
- Mark file or directory Read Only in Java
- Java Program to convert a Map to a read only map
- Java Program to convert a list to a read-only list
- How to make an ArrayList read only in Java?
- How to create a MongoDB collection using Java?
- Create a new ArrayList from another collection in Java
- Create Ennead Tuple from a List collection in Java
Advertisements