
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
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);
Advertisements