wood burning stoves*
The moose likes Beginning Java and the fly likes Add Strings in HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Add Strings in HashMap" Watch "Add Strings in HashMap" New topic
Author

Add Strings in HashMap

renu richard
Ranch Hand

Joined: Oct 06, 2008
Posts: 116
Hi,

I want to create a HashMap which is having the key as 1,2,3..... and the value as strings. When i try adding it, i could find only the put method whioch takes only the objects as the input. Can anyone please tell me hiow can i add these strings and integer values into the hashmap table. Thanks.


Cheers,
Richard
Pawel Nowacki
Ranch Hand

Joined: Nov 14, 2008
Posts: 67
You mean this put? :
http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html#put(java.lang.Object,%20java.lang.Object)

You can put here Integer and String. You can't put explicit primitives there.
renu richard
Ranch Hand

Joined: Oct 06, 2008
Posts: 116
Yes. This put method only.

Error i am getting is "No match was found for the method put(int, java.lang.String) in type java.util.HashMap
Pawel Nowacki
Ranch Hand

Joined: Nov 14, 2008
Posts: 67
You can't put int in there as it expects Object. So i guess you should wrap your int in Integer...
Balagopal Kannampallil
Ranch Hand

Joined: Oct 18, 2004
Posts: 136

Hi Renu,

With Java 1.5 came autoboxing and generics. You can do it in two ways.
Using generics


You can use this without generics also. Like this


If you are still sticking on to 1.4, you can write it like this
[edit]Add newlines to keep all text within screen width. CR[/edit]


SCJP 5.0 and now fighting with ExtJS
renu richard
Ranch Hand

Joined: Oct 06, 2008
Posts: 116
Hi Bala,
Its Working.
I have added something like this.

Now i want to get the value of arraylength when i give the tempdate value.

I want to know how to which variable i can assign this to.Can i do something like

Thanks
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
renu richard wrote: . . . I want to know how to which variable i can assign this to.Can i do something like
Yes, as long as the compiler knows you are returning an Integer. It will work in Java5 if you declare the Map as Map<Something, Integer> and instantiate it with the types too. In Java1.4 and older, you would have to use a class cast and some method of the Integer class to get the value.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Add Strings in HashMap