• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

why dont i get an exception here?

 
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


when li can store only integers then is "a" getting added into it?
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
oh thanks Ankit
 
reply
    Bookmark Topic Watch Topic
  • New Topic