What change of JLS 6/7 causes the following unchecked code with collections and generics to work in Java 7? -
the following code
import java.util.*; import java.io.*; @suppresswarnings("unchecked") list<serializable> list = (list<serializable>) (list<?>) collections.singletonlist(new object()); (object el : list) { // -> classcastexception system.out.println(el); } is correct java (even though code suspicious). using javac , java 6 throws
exception in thread "main" java.lang.classcastexception: java.lang.object cannot cast java.io.serializable while runs without error when using javac , java 7.
is language change, fixed bug or hidden feature?
(note: code compiled eclipse runs without error on eclipse versions checked - helios kepler.)
you're polluting heap adding raw object collection (which you're having cast dance make happen). it's not technically illegal, bug.
when pulling value out of implicit iterator, java 6 compiler appears casting immediately, while java 7 compiler isn't. it's more efficient not cast serializable if doesn't need (since holding variable object), behavior undefined far understand jls. try running javap on 2 .class files , looking @ code right around for loop (probably right after invokeinterface call iterator.next()).
Comments
Post a Comment