Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem regarding HashMap.

 
Rajesh Lohani
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 ?
 
Matthew Brown
Bartender
Posts: 4566
8
  • 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.

 
vedika ashtekar
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.
 
Ikpefua Jacob-Obinyan
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic