Java Collections unmodifiableSet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Collections

Definition

In Java, Collections.unmodifiableSet(s) returns a read-only view of a set. Lookups such as contains work, while add, remove, retainAll, and the rest throw UnsupportedOperationException.

A classic use is a static final constant of allowed values: build the set once, wrap it, and no code anywhere can quietly add to it.

A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.unmodifiableSet(...), after import java.util.Collections;. You never create a Collections object.

Syntax

Wrap a freshly built set to create a constant.

Java
static final Set<String> IMAGE_TYPES =
    Collections.unmodifiableSet(new TreeSet<>(Arrays.asList("gif", "jpg", "png")));
CallWhat it does
unmodifiableSet(s)Read-only view; iteration order follows s.
view.contains(x)Fast membership test, same as on s.
new TreeSet<>(view)Changeable copy for set algebra.
Set.of(...)Java 9+ immutable set; no null, no duplicates allowed in the call.

Available since Java 1.2. Unlike unmodifiableCollection, this view uses set equality, so it equals any set with the same elements.

Library declarations
Java
// java.util.Collections
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)

Parameters

ParameterDescription
sThe set to expose read-only. Must not be null.

Return Value

Return ValueDescription
Set<T>A read-only view of s.

Compare with Similar Methods

Related sets:

MethodHow it differs
unmodifiableSortedSet(s)Also keeps first, last, and range views.
singleton(x)Immutable set of exactly one element.
synchronizedSet(s)Thread-safe, still changeable.

Java Examples

Example 1 — A Constant Set of Allowed File Types

Check file extensions against a static final read-only set.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

public class CollectionsUnmodifiableSetConstant {
    static final Set<String> IMAGE_TYPES =
        Collections.unmodifiableSet(new TreeSet<>(Arrays.asList("gif", "jpg", "png")));

    static boolean isImage(String file) {
        String ext = file.substring(file.lastIndexOf('.') + 1);
        return IMAGE_TYPES.contains(ext);
    }

    public static void main(String[] args) {
        System.out.println("allowed: " + IMAGE_TYPES);
        System.out.println("cat.png -> " + isImage("cat.png"));
        System.out.println("notes.txt -> " + isImage("notes.txt"));
        try {
            IMAGE_TYPES.add("exe");
        } catch (UnsupportedOperationException e) {
            System.out.println("add exe: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Built once. The TreeSet is created inline, so the only reference to it is inside the wrapper.
  2. Lookups. isImage takes the text after the last dot; "png" is in the set and "txt" is not.
  3. Locked. Sneaking "exe" into the allowed list throws UnsupportedOperationException.

Example 2 — Find Common Elements Without Touching the View

retainAll computes an intersection in place, which a read-only set cannot do. Do it on a copy.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

public class CollectionsUnmodifiableSetAlgebra {
    public static void main(String[] args) {
        Set<String> mine = Collections.unmodifiableSet(new TreeSet<>(Arrays.asList("go", "java", "rust")));
        Set<String> theirs = new TreeSet<>(Arrays.asList("java", "kotlin", "rust"));

        try {
            mine.retainAll(theirs);
        } catch (UnsupportedOperationException e) {
            System.out.println("retainAll on view: " + e.getClass().getSimpleName());
        }
        Set<String> common = new TreeSet<>(mine);
        common.retainAll(theirs);
        System.out.println("common: " + common + ", mine: " + mine);
    }
}

How It Works

  1. In-place operation. retainAll would delete "go" from mine, so the view throws.
  2. Copy first. A new TreeSet built from the view is free to shrink.
  3. Result. The copy keeps the two shared languages, and the read-only set still has all three.

Example 3 — The View Equals Any Set with the Same Elements

Compare a read-only TreeSet view with a LinkedHashSet that holds the same numbers in a different order.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class CollectionsUnmodifiableSetEquality {
    public static void main(String[] args) {
        Set<Integer> a = Collections.unmodifiableSet(new TreeSet<>(Arrays.asList(3, 1, 2)));
        Set<Integer> b = new LinkedHashSet<>(Arrays.asList(3, 1, 2));

        System.out.println("a = " + a + ", b = " + b);
        System.out.println("a.equals(b): " + a.equals(b) + ", b.equals(a): " + b.equals(a));
        System.out.println("a.containsAll(b): " + a.containsAll(b));
    }
}

How It Works

  1. Different order. The view prints in the TreeSet's sorted order; the LinkedHashSet keeps insertion order 3, 1, 2.
  2. Set contract. Sets are equal when they hold the same elements, whatever their class or order, and the wrapper keeps that rule in both directions.
  3. Contrast. An unmodifiableCollection view would answer false here, because it compares by identity; containsAll confirms the elements match.

Frequently Asked Questions

It returns a read-only view of a Set. contains and iteration work; changes throw UnsupportedOperationException.
static final Set<T> X = Collections.unmodifiableSet(new TreeSet<>(Arrays.asList(...))); or Set.of(...) in Java 9+.
Yes, if code still holds the original set and modifies it. Wrap a set that nothing else references.
Yes, when they contain the same elements. The view follows the Set.equals contract.
Set.of (Java 9+) is a compact immutable set that rejects null and duplicates in the call; unmodifiableSet wraps any set you choose, on any Java version.

Next: unmodifiableSortedMap()

Wrap a SortedMap in a read-only view, including its range views.

unmodifiableSortedMap() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful