Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS 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
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Map....

 
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
source: www.javabeat.net


why it is giving classcast exception...?

and here we mention map with <Integer,String>
how can we store integer object in to String in for loop?

[ December 23, 2008: Message edited by: Ganeshkumar cheekati ]
[ December 23, 2008: Message edited by: Ganeshkumar cheekati ]
 
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static void populate(Map m)
{
for(int i=0;i<10;i++)
{
m.put(i,i);

At this line you are putting m.put(Integer,Integer), while map needs to put(Integer, String)


}
}

So when you call this line
System.out.println(map.get(1)+sap.get(1));

map.get(1); it will return Integer but JVM will try to cast it to String, that is called ClassCastException.
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

and here we mention map with <Integer,String>
how can we store integer object int to String in for loop?



static void populate(Map m)

see here we are not using generic code, we are using legacy code that can take put any Object in the Map.
If we have used (Map<Integer,String> m), then you will not be able to put int in place of String.


{
for(in i=0;i<10;i++)
{
m.put(i,i);

it is adding m.put(Integer,Integer), not put(int,int), and Integer is an Object also.


}
}
 
No holds barred. And no bars holed. Except this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic