Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
collections
view
communitycreator

What is UnmodifiableCollection in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The unmodifiableCollection method of the Collections class is used to return an unmodifiable view of a specified collection.

Query operations on the returned collection “read through” to the specified collection and attempt to modify the returned collection, whether direct or via its iterator, resulting in an UnsupportedOperationException.

Collections is defined in the util package in Java, so you must import the util package before you can use the unmodifiableCollection method, as shown below.

import java.util.Collections;

Syntax

The syntax for the unmodifiableCollection is shown below.

Collections.unmodifiableCollection(collection)

Method Signature

public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)

Parameters

Collection<? extends T> c: the collection for which an unmodifiable view is to be returned.

Example

In the code below, we define a list and add elements to the list. Next, we create an unmodifiable collection out of the list using unmodifiableCollection function. The method throws exception when we try to add a new element to the returned collection.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("hello");
stringList.add("hi");
stringList.add("world");
System.out.println(stringList);
Collection<String> list = Collections.unmodifiableCollection(stringList);
list.add("hello");
}
}

RELATED TAGS

java
collections
view
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring