Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Add Strings in HashMap

 
renu richard
Ranch Hand
Posts: 116
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Pawel Nowacki
Ranch Hand
Posts: 67
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 116
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 67
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 136
Firefox Browser Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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]
 
renu richard
Ranch Hand
Posts: 116
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47232
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic