Menu

Java Tricky Question: Why Does This List Crash With ClassCastException When There Is No Cast in the Code?
📰

Java Tricky Question: Why Does This List Crash With ClassCastException When There Is No Cast in the Code?

DEV Community: java·Vishnu B·about 12 hours ago
#8SV6qPdp
#devtojava#devto#dev#java#list
Long article (1193 words) — no AI summary yet.
Reading 0:00
15s threshold

Here is a scenario that has confused many Java developers, because the line that crashes contains no cast at all. Look at this program and predict what it does.

import java . util . ArrayList ; import java . util . List ;

public class TrickyDemo { public static void main ( String [ ] args ) { List < Integer > numbers = new ArrayList <> ( ) ; numbers . add ( 1 ) ;

List raw = numbers ; // hand the same list to a raw-typed reference raw . add ( "not a number" ) ; // compiles, believe it or not

for ( Integer n : numbers ) { System . out . println ( "got " + n ) ; // no cast written anywhere here } } }

Enter fullscreen mode

Exit fullscreen mode

Pick your answer:

A) Compile error: you cannot put a String into a List of Integer

B) It compiles, and crashes inside raw.add(...) when the String goes in

C) It prints 1, then crashes at the for loop with ClassCastException

D) It prints 1 and "not a number" and finishes happily

The answer

I compiled and ran this exact program on JDK 21 (Temurin 21.0.13).…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.