Home Java Collections Methods checkedSet() Java Collections checkedSet() Method 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.
Set<String> tags = Collections.checkedSet(new LinkedHashSet<String>(), String.class);
Set raw = tags;
raw.add(2026); // ClassCastException Call What 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.util.Collections
public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) Parameters Parameter Description sThe set to protect. typeThe class or interface every element must be an instance of.
Return Value Return Value Description Set<E>A dynamically type-safe view of s.
Compare with Similar Methods Related wrappers:
Java Examples 1. Raw add 2. Interface type 3. Unchecked cast 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.
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 Normal use. Generic code adds two tags, which are kept in insertion order by the LinkedHashSet.Number blocked. The raw reference tries to add the Integer 2026 and gets ClassCastException.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.
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);
}
} Character: ClassCastException
[plain, built] How It Works Interface as type. String and StringBuilder both implement CharSequence, so both are stored.Close but wrong. 'c' is boxed to Character, which does not implement CharSequence, so it is rejected.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>.
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);
}
} addAnything: ClassCastException
[A1] How It Works Unchecked cast. Casting through Set<?> compiles with only a warning, because generic types are erased at runtime.Innocent method. addAnything is correct for a Set<Object>, so it happily adds an Integer.Runtime guard. The checked wrapper still knows its element type is String and throws, so the set stays clean.Frequently Asked Questions What does Collections.checkedSet() do? It returns a Set view that throws ClassCastException when an element of the wrong type is added.
Can the type be an interface? Yes. Any class implementing the interface passes, for example String and StringBuilder for CharSequence.
Does checkedSet() protect against unchecked casts? Yes. The wrapper checks at runtime, so it catches wrong types added through raw types, unchecked casts, or reflection.
Can checkedSet() check generic element types like List<String>? No. Because of type erasure it can only check the raw class, such as List.
Which Java version added checkedSet()? Java 5.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion