why dont i get an exception here?

scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later"....by someone unknown

Sebastian Janisch

Ranch Hand

Posts: 1183

posted 7 years ago

Your second list is not parameterized which means you can shred whatever object you like into the list.
The big bang will happen once you want to retrieve values back from the list trying to convert them in what you expect to be an integer.

The reason why this works is the downwards compatability with older java versions and programs. It's ugly and error prone so never work with unparameterized collections.

Now you'll get an exception. As you know generics is all about compile time type safety. So you won't get any exception when you add a String to an <Integer> List. Because a typed collection can have any type of elements added to it if you can fool the compiler, as for the JVM a typed collection is not different from raw collection. When you get an element out of a typed collection, the compiler inserts a type caste at that statement. So in the above case the compiler inserts a cast which results in an exception. The actual code which the JVM sees looks something like this

When you used a println statement, you didn't get any exception because the println method takes Object as a parameter, so the compiler doesn't inserts any cast...