Win a copy of Svelte and Sapper in Action this week in the JavaScript 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
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Map Question

 
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 .


 
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
 
author
Posts: 23883
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux 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
 
    Bookmark Topic Watch Topic
  • New Topic