How to create Readonly Collections

Read Only Collections


Following methods available in Collections class to make the collections as read only.

The Collections class has six methods to help out here:
1. unmodifiableCollection(Collection c)
2. unmodifiableList(List list)
3. unmodifiableMap(Map m)
4. unmodifiableSet(Set s)
5. unmodifiableSortedMap(SortedMap m)
6. unmodifiableSortedSet(SortedSet s)
If you get an Iterator from one of these unmodifiable collections, when you call remove(), it will throw an UnsupportedOperationException.

Example

package com.search;

import java.util.*;

public class ReadOnlyCollections {
    public static void main(String[] args) {
        List ar = new ArrayList();
        ar.add("Vinod");
        ar.add("Raj");
        ar.add("Raghav");
        ar.add("Santhosh");
        System.out.println("Before removal " + ar);
        ar = Collections.unmodifiableList(ar);
        Iterator<String> it = ar.iterator();
        while (it.hasNext()) {
            String name = it.next().toString();
            if (name.equals("Raj")) {
                it.remove();
            }
        }
        System.out.println("After removal " + ar);
    }

}

Output
Before removal [Vinod, Raj, Raghav, Santhosh] Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection$1.remove(Unknown Source) at com.search.ReadOnlyCollections.main(ReadOnlyCollections.java:18)

 

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts