我在将HashMap中的每个值转换为String时遇到了一些麻烦。
private static HashMap<String, List<Music>> musiksammlung = new
HashMap<String, List<Music>>();
这是我对HashMap的构造函数。键代表专辑,价值是该专辑的曲目列表 现在我想将每个Music对象转换为String而不创建新的HashMap,就是这样 可能? 我已尝试使用Iterator方案,在入口集上循环,等等但似乎没有任何效果。
编辑://
我的convertmethod代码:
public HashMap<String, List<String>> generateFormatList() {
HashMap<String, List<String>> formatList = new HashMap<String, List<String>>();
for(String key : musiksammlung.keySet())
formatList.put(key, musiksammlung.get(key).toString());
return musiksammlung;
}
但这总是会导致错误&#34;不适用于Arguments(String,String),所以我不知道。我是否必须覆盖toString()?
答案 0 :(得分:0)
您的路径正确,但您需要将现有的List<Music>
转换为List<String>
并将List<String>
放入新的HashMap
。
然后,您还想要返回新创建的HashMap<String, List<String>>
而不是原始的{。\ n}。
public HashMap<String, List<String>> generateFormatList() {
HashMap<String, List<String>> formatList = new HashMap<String, List<String>>();
for(String key : musiksammlung.keySet()) {
// Value to store in map
List<String> value = new ArrayList<String>();
// Get the List<Music>
List<Music> musicList = musiksammlung.get(key);
for (Music m: musicList) {
// Add String of each Music object to the List
value.add(m.toString);
}
// Add the value to your new map
formatList.put(key, value);
}
// Return the new map
return formatList;
}
所以回答你的问题:
现在我想将每个Music对象转换为String而不创建 新的HashMap,这可能吗?
您需要创建一个新的HashMap
,因为它存储的是不同类型的值:List<Music>
与List<String>
不同。
同样如我之前的回答中所述,请确保覆盖Music.toString()
,以便为您返回有意义的String
,而不是从其父类继承的那个,其中至少包括{{} 1}}
答案 1 :(得分:0)
尝试像这样更改HashMap
:
private static HashMap<String, List<Object>> musiksammlung = new HashMap<String,List<Object>>();
因此,您可以在此HashMap
中保存任何类型的对象。在使用对象之前,还要使用instanceof
检查对象的类型。
答案 2 :(得分:0)
formatList
需要List<String>
,但musiksammlung.get(key).toString()
会返回String
(而不是List<String>
)。你是说这个吗?
HashMap<String, String> formatList = new HashMap<String, String>();
答案 3 :(得分:0)
你有没有试过这样的事情:
Iterator<String> it = musiksammlung.keySet().iterator();
while (it.hasNext()) {
List<Music> ml = musiksammlung.get(it.next());
for (Music m : ml)
System.out.println(m.toString());
}
当然你应该用你可以使用的东西覆盖Music#toString()方法。