Java Challenge Answer (3)

Hi,

so, did anyone put the code to run in Eclipse??

If you did it, you could see that the code is correct… it doesn’t fail in any of its parts, but why? It is really strange, because we are a assigning a String inside a list of Integer and it would fail at runtime, don’t you think?

To answer this challenge, you must be very familiar with Generics in Java 5, because somethings in Generics don’t make sense, like the code that I posted here. So, this is what happens:

Because of the legacy code before Generics, JVM has no ideia that my ArrayList was supposed to hold only Integers. The typing information does not exist at runtime. All Generics code is strictly for the compiler, which does all the verifications on Generics code and then strips the type information out of the class bytecode, exactly like pre-generics version of collection. None of the protections of Generics exists at runtime.

This is what JVM sees after the compilation: List myList = new ArrayList();So, JVM does not have any reason to throw away runtime exceptions.

Really surprising, doesn’t it?


Fernando

One thought on “Java Challenge Answer (3)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s