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

Map Question

 
Akhil Maharaj
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello ,

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


 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21000
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic