Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Problem regarding HashMap.

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have the following code :


As map1 is generic and will take key as String,value as Integer so whats the reason that the above code is not giving compile/run time problem ?
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you're mixing generic and non-generic code.

The compiler lets you do it because when generics were introduced they were designed to be backwards compatible. So it will let you add the non-generic Map to the generic one. I would expect you to see a warning, but it won't actually stop you.

At run-time it works because of type-erasure - the generic information doesn't exist at run-time. You'd only get an exception if you tried to extract the key and assign it to a String - then you'd get a ClassCastException.

The bottom line is - don't do it. Always use generics, unless you are forced to work with existing classes that don't.
 
Rajesh Lohani
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the info and for clearing my doubts Matthew.

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Rajesh Lohani wrote:Thanks for the info and for clearing my doubts Matthew.



Hi Mattthew,
even i was trying to find the reason behind it. but I could not. Thanks for explaining.
But I could not understand what do you mean by type-erasure ? Kindly explain please.
 
Ranch Hand
Posts: 394
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Vedika, 'Type-Erasure' means this; '<String,Integer>' is NO longer available at runtime.

Regards

Ikpefua.
 
vedika ashtekar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh ! yes I understood it.

Thanks a lot Ikpefua.

 
    Bookmark Topic Watch Topic
  • New Topic