Course contentsShow
← Java
Lesson 1262 of 2,87028. Collections Utility ClassFree lesson

Collections.checkedCollection and Type Safety

Wrap collections with runtime type checking using checkedList, checkedSet, and checkedMap methods.

Collections.checkedCollection and Type Safety

What you'll learn: How to wrap collections with runtime type checks to prevent accidental insertion of wrong types.

The Type Safety Problem

Java's generics are erased at runtime — the JVM doesn't actually know that your List<String> should only hold strings. If you obtain a raw reference to a generic collection (common when working with legacy code or reflection), you can accidentally insert the wrong type, causing a ClassCastException much later when you retrieve elements.

Checked Collection Wrappers

The Collections class provides checked wrappers that validate element types at insertion time:

  • Collections.checkedList(list, String.class) — wraps a list with runtime type checking
  • Collections.checkedSet(set, Integer.class) — wraps a set
  • Collections.checkedMap(map, String.class, Integer.class) — wraps a map (key and value types)
  • Collections.checkedCollection(collection, MyClass.class) — generic wrapper for any collection

These methods take the collection to wrap and the Class object representing the expected element type. They return a dynamically type-checked view that throws ClassCastException immediately if someone tries to insert a wrong type.

When to Use This

Checked collections are most valuable when:

  • Interfacing with legacy code that uses raw types
  • Passing collections to untrusted code
  • Debugging mysterious ClassCastException errors that happen far from the actual mistake

Think of checked collections as runtime guardrails for your type safety — they catch type violations at the source rather than when you later trip over corrupted data.

Key Takeaway:
Use Collections.checkedList, checkedSet, and checkedMap to enforce type safety at runtime, catching incorrect insertions immediately rather than later during retrieval.