6

I am trying to create a list of key-value pairs. Here is what I have so far:

Map<Integer,String> map = new HashMap<Integer,String>().put(songID, songList.get(i).name);

This gives me the following error:

Type mismatch: cannot convert from String to Map

Also, how would I iterate through these? Thanks!

john cs
  • 2,220
  • 5
  • 32
  • 50

2 Answers2

16

When you call put on the map of type Map <Integer,String>, you will get the String returned. So when you do this:

new HashMap<Integer,String>().put(songID, songList.get(i).name);

it will return a String

and when you try to assign it to a map

Map<Integer,String> map 

compiler throws an error,

Type mismatch: cannot convert from String to Map

Here is the signature of put method form javadocs:

public V put(K key,
             V value)

you need to break down the this complex problematic statement:

Map<Integer,String> map = new HashMap<Integer,String>().put(songID, songList.get(i).name);

to something like:

Map<Integer,String> map = new HashMap<Integer,String>();

map.put(songID, songList.get(i).name);
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • 1
    thank you for breaking the problem down and explaining it step by step. i was confused with the two steps initially when I saw it on another question. – john cs Aug 24 '13 at 04:02
  • You can also exploit anonymous inner classes when you need to. But I hear that not everyone is comfortable with them. – dans3itz Aug 24 '13 at 04:04
0

The answer on this thread: Java HashMap associative multi dimensional array can not create or add elements

has an example of how to do this.

Community
  • 1
  • 1
Daniel Gabriel
  • 3,939
  • 2
  • 26
  • 37
  • 1
    Frankly, I'm not sure how your answer pertains to the question. (I never down voted btw) – Josh M Aug 24 '13 at 03:59
  • It pertains to the question because it contains an example of how to solve this problem. The example shows how to create a HashMap and put multiple key-value pairs into it. – Daniel Gabriel Aug 24 '13 at 03:59
  • 1
    I didn't vote down on this either (just upvoted) but that page had a lot of information, thank you! I saw a lot of similar pages but missed that one. Will edit my initial post with answer. – john cs Aug 24 '13 at 04:01