liveBook · Manning

Unchecked/Unconfirmed Cast warning

As explained in 100 Java Mistakes and How to Avoid Them

An unchecked cast warning is a compiler diagnostic indicating that a cast involving generic types cannot be verified for type safety.

An Unchecked/Unconfirmed Cast warning flags a cast whose safety cannot be established reliably. Ordinary casts can fail immediately, but generic casts may hide danger until a later operation retrieves an element. section 5.3.1 section 5.3.2

A generic cast creates a time bomb

A List<String> can be viewed as List<?> and then unsafely cast to List<Object>. Adding an Integer does not fail because generic type arguments are erased at runtime; printFirstItem later retrieves the value as String and can fail. section 5.3.2

Reduce unchecked and unnecessary casts by applying these rules:

  • Prefer concrete variable types so static checking can remove casts entirely. section 5.3.1
  • Guard ordinary casts with instanceof; since Java 16, use pattern matching to test and bind the target type once. section 5.3.1
  • Use wildcard bounds or unmodifiable views when a method only needs to read a collection, rather than forcing an invariant generic cast. section 5.3.2
  • Treat static-analysis findings as useful leads, not absolute proof: IntelliJ IDEA and SpotBugs can report false positives. section 5.3.1
List<String> list = new ArrayList<>();
List<?> objects = list;
((List<Object>) objects).add(1);     #1
printFirstItem(list);

Trace how an unchecked List cast permits an invalid element and postpones the failure. section 5.3.2

if (obj instanceof MyType myType) {
  … // Use myType.
}

Compare a traditional instanceof guard and cast with Java 16 pattern matching. section 5.3.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains ordinary and generic cast failures, runtime erasure, delayed consequences, and practical avoidance, while noting rare unavoidable casts.
Examples
Uses invalid List<String> mutation, delayed string retrieval, instanceof casts, pattern matching, and safer collection APIs.
What it assumes
Assumes familiarity with Java casts, generics, lists, instanceof, and method calls.
What you can do after
Diagnose/debug with compiler and IDE warnings, then replace risky casts with static types, guards, wildcard bounds, or checked collections.
How it connects
Connects Java generics, type erasure, instanceof, ClassCastException, wildcard bounds, and static analysis.

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.