Collections: Collections.checkedList catches a raw-type mistake early

A checked wrapper validates every insertion's runtime type immediately, throwing ClassCastException at the point of the bad add instead of letting a wrong-typed element surface later as a mysterious cast failure.

Code
List<String> strings = new ArrayList<>();
List<String> checked = Collections.checkedList(strings, String.class);
checked.add("ok");
System.out.println("Added fine: " + strings);
// Simulate legacy raw-typed code calling add(Object) through reflection.
try {
    List.class.getMethod("add", Object.class).invoke(checked, 42);
} catch (java.lang.reflect.InvocationTargetException e) {
    System.out.println("checkedList rejects the wrong type: " + e.getCause().getClass().getSimpleName());
}
System.out.println("List is still clean: " + strings);
Output
Added fine: [ok]
checkedList rejects the wrong type: ClassCastException
List is still clean: [ok]
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms