File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem regarding HashMap. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem regarding HashMap." Watch "Problem regarding HashMap." New topic
Author

Problem regarding HashMap.

Rajesh Lohani
Greenhorn

Joined: May 14, 2010
Posts: 8
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 ?


" I don't believe in failure. It is not failure if you enjoyed the process. " - Rajesh Lohani
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4240
    
    7

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

Joined: May 14, 2010
Posts: 8
Thanks for the info and for clearing my doubts Matthew.

vedika ashtekar
Greenhorn

Joined: Dec 15, 2008
Posts: 19
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

Joined: Aug 31, 2010
Posts: 394

Hello Vedika, 'Type-Erasure' means this; '<String,Integer>' is NO longer available at runtime.

Regards

Ikpefua.


OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
vedika ashtekar
Greenhorn

Joined: Dec 15, 2008
Posts: 19
Oh ! yes I understood it.

Thanks a lot Ikpefua.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem regarding HashMap.
 
Similar Threads
Q on TreeMap
HashMap Problem
Fetch multiple keys at one go
How to refresh a StringBuffer object for creating a HashMap object
HashMap values-- I think I know why but how do I fix this null pointer exception?