Java generics are checked only at compile time. Through a raw reference or an unchecked cast, an Integer can slip into a Collection<String>, and nothing complains until some later code reads it as a String.
Collections.checkedCollection(c, type) returns a wrapper that checks every inserted element at runtime with type.isInstance. A bad element triggers ClassCastException right at the faulty add, which makes the bug easy to find.
A static method of the java.util.Collections utility class, available since Java 5. Call it on the class name, as in Collections.checkedCollection(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Pass the collection and the element's Class object.
Java
Collection<String> names =
Collections.checkedCollection(new ArrayList<String>(), String.class);
Collection raw = names;
raw.add(42); // ClassCastException right here
Call
What it does
checkedCollection(c, String.class)
Only String (or null) may be added.
checkedCollection(c, Number.class)
Subclasses such as Integer and Double are accepted.
checked.addAll(other)
Every element is type-checked before any is added.
checked.remove(x) / clear()
Removals are not restricted.
Added in Java 5, together with generics. The JDK documentation suggests it as a debugging aid: wrap a collection temporarily to find the code that inserts a wrong type.
Library declarations
Java
// java.util.Collections
public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type)
Parameters
Parameter
Description
c
The collection to protect. Use only the wrapper afterwards.
type
The element class every inserted element must be an instance of.
plain accepted it, size 1
plain fails when read: ClassCastException
checked fails at insert: ClassCastException, size 0
How It Works
Raw back door.legacyAdd takes a raw Collection, so the compiler cannot stop it adding 42 to a collection of strings.
Delayed failure. The plain list stores the Integer; the error only appears in the loop, where Java casts each element to String. In a real program that could be far from the bug.
Immediate failure. The checked wrapper tests the element inside add, throws at the guilty line, and stores nothing.
Example 2 — A Mixed addAll Adds Nothing
Add a raw list containing one bad element. The wrapper rejects the whole batch.