Java 创建键值对象列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18414747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:24:37  来源:igfitidea点击:

Create a list of key value objects

javadata-structureshashmapkey-value

提问by john cs

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

类型不匹配:无法从 String 转换为 Map

Also, how would I iterate through these? Thanks!

另外,我将如何遍历这些?谢谢!

采纳答案by Juned Ahsan

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

当您调用puttype 的地图时Map <Integer,String>,您将获得返回的字符串。所以当你这样做时:

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

it will return a String

它会返回一个 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

类型不匹配:无法从 String 转换为 Map

Here is the signature of put method form javadocs:

这是javadocs中 put 方法的签名:

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);

回答by Daniel Gabriel

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

此线程的答案: Java HashMap 关联多维数组无法创建或添加元素

has an example of how to do this.

有一个如何做到这一点的例子。