Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Make a Collection Read-Only in Java?
Next article icon

How to Make a Collection Read-Only in Java?

Last Updated : 11 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

The Collections class is used as a data structure to manage the data. We can add, remove, fetch, and update the data in the List, Set, or Map Object. Collections class has default methods for these operations. We can use those methods easily. By default, when we create an object of the Collections class, it will be Both Readable and Writable.

Read-only Collection: To make the object of Collections to Read-Only, we need to restrict an object to add, remove, or update data from it. The only operation is to fetch the data.

Java has different methods for different Collection type like unmodifiableCollection(), unmodifiableMap(), ununmodifiableSet() e.t.c. All the methods are predefined in java.util.Collections class.The unmodifiableCollection() is a generic method to make Read-Only collection. We need to make the reference of Collections class for that. If we have an object of Set Interface, we can use ununmodifiableSet() to make Read-Only.

Example 1: Below code shows how to make a List unmodifiable.

Java
// Java Program to make Collections Read-Only  import java.util.ArrayList; import java.util.Collections; import java.util.List;  public class GFG {      public static void main(String[] args)     {         // List of Integer         List<Integer> numbers = new ArrayList<>();          // List have 1 to 10 numbers         for (int i = 1; i <= 10; i++) {             numbers.add(i);         }          // Iterate on the stream of integers and         // print them         numbers.stream().forEach(System.out::print);          // Now we are adding one more element         numbers.add(11);          // Removing element from the list         numbers.remove(8);          // Updating List¶         numbers.set(4, 4);          System.out.println(             "\nAfter Performing Some Operations");          numbers.stream().forEach(System.out::print);          System.out.println(             "\nHence By default Collections object is Readable and Writable");          // Now making Read-Only List         // Using unmodifiableList() method.         try {             numbers = Collections.unmodifiableList(numbers);              // This line will generate an Exception             numbers.remove(11);         }         catch (UnsupportedOperationException                    unsupportedOperationException) {             System.out.println(                 "Exceptions is "                 + unsupportedOperationException);         }         finally {             System.out.println(numbers.get(3));             System.out.println(                 "Now list is only Read-Only");         }     } } 
Output
12345678910 After Performing Some Operations 123446781011 Hence By default Collections object is Readable and Writable Exceptions is java.lang.UnsupportedOperationException 4 Now list is only Read-Only

Above is an example of how to make a list Read-Only. Before making Read-Only we can perform CRUD operations but after making Read-only list, set(), add(), and remove() methods will generate Exceptions. We can now only fetch the data from the list.

Example 2: Below code shows how to make a Set unmodifiable. 

Java
// Java Program to make // Set Interface Object Read-Only  import java.util.Set; import java.util.HashSet; import java.util.Collections;  class GFG {      public static void main(String[] args)     {         // Set of Integer         Set<Integer> numbers = new HashSet<Integer>();          // Set have 1 to 10 numbers         for (int i = 1; i <= 5; i++) {             numbers.add(i);         }          // print the integers         numbers.stream().forEach(System.out::print);          // Removing element from the list         numbers.remove(5);          System.out.println("\nAfter Performing Operation");          numbers.stream().forEach(System.out::print);          System.out.println(             "\nSet is also By Default Readable and Writable");          // Now making Read-Only Set         // Using unmodifiableSet() method.         try {             numbers = Collections.unmodifiableSet(numbers);              // This line will generate an Exception             numbers.remove(4);         }         catch (UnsupportedOperationException                    unsupportedOperationException) {             System.out.println(                 "Exceptions is "                 + unsupportedOperationException);         }         finally {             System.out.println(numbers.contains(3));             System.out.println("Now Set is Read-Only");         }     } } 

Output
12345 After Performing Operation 1234 Set is also By Default Readable and Writable Exceptions is java.lang.UnsupportedOperationException true Now Set is Read-Only

In Above Example, We make Set as Read-Only. We can make Collections object Read-Only by using unmodifiableCollection() and to make Map Read-Only we can use unmodifiableMap() method. 

MethodDescription
static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)This method accepts any of the collection objects and returns an unmodifiable view of the specified collection.
static <T> List<T> unmodifiableList(List<? extends T> list)This method accepts an object of the List interface and returns an unmodifiable view of it.
static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)This method accepts an object of the Map interface and returns an unmodifiable view of it.
static <T> Set<T> unmodifiableSet(Set<? extends T> s)This method accepts an object of the Set interface and returns an unmodifiable view of it..
static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,? extends V> m)This method accepts an object of the SortedMap interface and returns an unmodifiable view of it.
static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)This method accepts an object of the SortedSet interface and returns an unmodifiable view of the specified sorted set.


 


Next Article
How to Make a Collection Read-Only in Java?

D

denesdvaghani9200
Improve
Article Tags :
  • Java
  • Java-Collections
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    How to make an ArrayList read only in Java
    Given an ArrayList, the task is to make this ArrayList read-only in Java. Examples: Input: ArrayList: [1, 2, 3, 4, 5] Output: Read-only ArrayList: [1, 2, 3, 4, 5] Input: ArrayList: [geeks, for, geeks] Output: Read-only ArrayList: [geeks, for, geeks] An ArrayList can be made read-only easily with the
    2 min read
    Collection add() Method in Java with Examples
    The add(E element) of java.util.Collection interface is used to add the element 'element' to this collection. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false. Syntax: Collection.add(E element) Paramet
    4 min read
    Need of Concurrent Collections in java
    In Java, multiple threads can work at the same time, but when the applications become complex, it is very important to handle multiple threads at the same time. With the help of concurrency, different tasks can run in parallel, which can improve the performance of the application. Managing shared da
    3 min read
    How to Learn Java Collections - A Complete Guide
    In the real world, a collection by definition is a group of articles that have similar properties and attributes. Since Java is an Object-Oriented Language it mimics the real world. In Java, a Collection is a group of multiple objects put together into a single unit. Java Collections is a very vast
    15+ min read
    Collection addAll() method in Java with Examples
    The addAll(Collection collection) of java.util.Collection interface is used to add the Collection 'collection' to this existing collection. This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false. Syntax:
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences