The following code
import java.util.*;
import java.io.*;
@SuppressWarnings("unchecked")
List<Serializable> list = (List<Serializable>) (List<?>)
Collections.singletonList(new Object());
for (Object el : list) { // -> ClassCastException
System.out.println(el);
}
is correct Java (even though the code is suspicious). Using javac
and java
6 it throws
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.io.Serializable
while it runs without error when using javac
and java
7.
Is it a language change, fixed bug or a hidden feature?
(Note: Code compiled with Eclipse runs without error on all Eclipse versions checked - Helios to Kepler.)