wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Map Question 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 "Map Question" Watch "Map Question" New topic
Author

Map Question

Akhil Maharaj
Ranch Hand

Joined: Sep 29, 2007
Posts: 63
Hello ,

Why I am getting Runtime exception at Line 1 in the follwing code .


ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
map.get(1)
Returns String but contains Integer, ClassCastException occur when you try to treat the returned value as String.

while nap.get(1)
Returns Object and contains Integer, passing it to the print statement will invoke object's toString().
Akhil Maharaj
Ranch Hand

Joined: Sep 29, 2007
Posts: 63
Ahmed ,

map.get(1)
Returns String but contains Integer
Agreed

, ClassCastException occur when you try to treat the returned value as String.
Agreed

Question : All I am doing here is trying to print the Integer Object that I get out of map.get(1) . I did not treat it as String Object

Any more comments will be of great help
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18760
    
  40

Question : All I am doing here is trying to print the Integer Object that I get out of map.get(1) . I did not treat it as String Object


Actually, you did. You declared the map as having strings as values (generics) -- and then you placed integers into them, by not using generics. So you effectively tricked the compiler into thinking that you were working with strings, and to use the println() method that took a string, instead of one that took an object.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Map Question