Win a copy of Spring in Action (5th edition) this week in the Spring 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
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Problem regarding HashMap.  RSS feed

 
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 Java Oracle
  • 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.

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!