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
