File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why  dont i get an exception here? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why  dont i get an exception here?" Watch "why  dont i get an exception here?" New topic

why dont i get an exception here?

Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521

when li can store only integers then is "a" getting added into it?

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

Joined: Feb 23, 2009
Posts: 1183
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.

JDBCSupport - An easy to use, light-weight JDBC framework -
Ankit Garg

Joined: Aug 03, 2008
Posts: 9466

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...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521
oh thanks Ankit
I agree. Here's the link:
subject: why dont i get an exception here?
It's not a secret anymore!