Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

trouble using Map/HashMap 1

Status
Not open for further replies.

sm43

Programmer
Dec 1, 2002
155
US

Hi,
If the Map class takes Object as parameters for all its methods, how can I put objects belonging to any other type into the map. For example, if I want to do:

Map a = new HashMap() ;

long id ;
String bookname ;

a.put(id,bookname) ;


It doesn't work..I get a compile error on the a.put line saying the parameter's types are wrong.. If I try casting the parameters to (Object) like

a.put((Object) id, (Object) bookname) ;

I get the error that the types cannot be casted into Object. I'm confused. All classes inherit from Object so why does the cast generate compile error. How do I accomplish the task above? If this is not it, what is the workaround? I thought Maps were so you could use them with any types..


Thanks.

Saad
 
Try creating an Integer object out of 'id' first then pass this object and the 'bookname' String to the 'a.put()' function call.
 
Thank you very much. Yes that's exactly what I did. Created a Long object from the long value & passed it to
put(). All classes inherit from Object, but the primitive types don't.


Thanks.

Saad
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top