• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why dont i get an exception here?

 
Raju Champaklal
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


when li can store only integers then is "a" getting added into it?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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...
 
Raju Champaklal
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh thanks Ankit
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic