Java Collections checkedSet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 5+

Definition

In Java, Collections.checkedSet(s, type) returns a Set wrapper that confirms every added element is an instance of type. A wrong element causes ClassCastException at the moment of insertion.

The type can be a class or an interface. With CharSequence.class, for instance, both String and StringBuilder are accepted.

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

Syntax

Pass the set and the element class.

Java
Set<String> tags = Collections.checkedSet(new LinkedHashSet<String>(), String.class);
Set raw = tags;
raw.add(2026);   // ClassCastException
CallWhat it does
checkedSet(s, String.class)Only strings (or null) may be added.
checkedSet(s, CharSequence.class)Any class implementing the interface.
raw.add(x) / addAll(c)Checked.
remove / retainAll / clearNot restricted.

Added in Java 5. Equality and iteration order come from the wrapped set, so wrapping a LinkedHashSet keeps insertion order.

Library declarations
Java
// java.util.Collections
public static <E> Set<E> checkedSet(Set<E> s, Class<E> type)

Parameters

ParameterDescription
sThe set to protect.
typeThe class or interface every element must be an instance of.

Return Value

Return ValueDescription
Set<E>A dynamically type-safe view of s.

Compare with Similar Methods

Related wrappers:

MethodHow it differs
checkedSortedSet(s, type)Type-checked sorted set.
checkedCollection(c, type)For any collection.
unmodifiableSet(s)Blocks all writes.

Java Examples

Example 1 — Keep a Tag Set Free of Numbers

A raw reference adds a year to a set of tags; the checked set refuses it.

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

public class CollectionsCheckedSetTags {
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void main(String[] args) {
        Set<String> tags = Collections.checkedSet(new LinkedHashSet<String>(), String.class);
        tags.add("java");
        tags.add("tips");

        Set raw = tags;
        try {
            raw.add(2026);
        } catch (ClassCastException e) {
            System.out.println("add 2026: " + e.getClass().getSimpleName());
        }
        raw.add("news");
        System.out.println(tags + " size " + tags.size());
    }
}

How It Works

  1. Normal use. Generic code adds two tags, which are kept in insertion order by the LinkedHashSet.
  2. Number blocked. The raw reference tries to add the Integer 2026 and gets ClassCastException.
  3. Strings still fine. Adding "news" through the same raw reference passes the check.

Example 2 — Check Against an Interface

Accept anything that is a CharSequence, but not a single Character.

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

public class CollectionsCheckedSetInterface {
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void main(String[] args) {
        Set<CharSequence> texts = Collections.checkedSet(new LinkedHashSet<CharSequence>(), CharSequence.class);
        texts.add("plain");
        texts.add(new StringBuilder("built"));

        Set raw = texts;
        try {
            raw.add('c');
        } catch (ClassCastException e) {
            System.out.println("Character: " + e.getClass().getSimpleName());
        }
        System.out.println(texts);
    }
}

How It Works

  1. Interface as type. String and StringBuilder both implement CharSequence, so both are stored.
  2. Close but wrong. 'c' is boxed to Character, which does not implement CharSequence, so it is rejected.
  3. Printing. The set prints each element's text, giving plain and built.

Example 3 — Catch Heap Pollution from an Unchecked Cast

No raw types this time: a double cast turns a Set<String> into a Set<Object>.

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

public class CollectionsCheckedSetCast {
    static void addAnything(Set<Object> s) {
        s.add(Integer.valueOf(1));
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        Set<String> codes = Collections.checkedSet(new LinkedHashSet<String>(), String.class);
        codes.add("A1");

        Set<Object> sneaky = (Set<Object>) (Set<?>) codes;
        try {
            addAnything(sneaky);
        } catch (ClassCastException e) {
            System.out.println("addAnything: " + e.getClass().getSimpleName());
        }
        System.out.println(codes);
    }
}

How It Works

  1. Unchecked cast. Casting through Set<?> compiles with only a warning, because generic types are erased at runtime.
  2. Innocent method. addAnything is correct for a Set<Object>, so it happily adds an Integer.
  3. Runtime guard. The checked wrapper still knows its element type is String and throws, so the set stays clean.

Frequently Asked Questions

It returns a Set view that throws ClassCastException when an element of the wrong type is added.
Yes. Any class implementing the interface passes, for example String and StringBuilder for CharSequence.
Yes. The wrapper checks at runtime, so it catches wrong types added through raw types, unchecked casts, or reflection.
No. Because of type erasure it can only check the raw class, such as List.
Java 5.

Next: checkedSortedMap()

Wrap a SortedMap so wrong key or value types are rejected, including in sub-maps.

checkedSortedMap() 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.

7 people found this page helpful