如何将HashMap值传递给列表
问题描述:
如何将hashmap值传递到列表 条目的类型是String键和值吗?如何将HashMap值传递给列表
页面类:
public List<Entry> entry;
public void setEntry(final List<Entry> entry) {
this.entry = entry;
this.setInfo(entry);
}
public void setInfo(final List<Entry> entryList) {
this.prop = new HashMap<String, String>();
for (Entry objEntry : this.entry) {
this.prop.put(objEntry.getKey(), objEntry.getValue());
}
}
我创建了一个地图:
Map<String, String> info = new HashMap<String, String>();
info.put("abc", "123")
我尝试这样做:
List l = new ArrayList(info.values());
page.setInfo(list); // I am getting class cast exception
答
在你的public void setInfo(final List<Entry> entryList)
方法,需要一个类型的List<Entry>
,而你通过的类型是List<String>
。
如果您是通用的,请检查here了解更多信息。
因此,对于您的情况,您需要列表中的Entry类型。方法图#entrySet()
可以做到这一点,它返回一个Map.Entry的集合。
你可以这样设置项创建列表:
List<Entry> list = new ArrayList(info.entrySet());
答
在Page类setInfo方法,enhanced for loop
尝试更换this.entry到entryList为:
页面类:
class Page {
public List<Entry> entry;
...
public void setInfo(final List<Entry> entryList) {
this.prop = new HashMap<String, String>();
for (Entry objEntry : entryList) {
this.prop.put(objEntry.getKey(), objEntry.getValue());
}
}
}
创建您的列表,设置为:(按@Jaskey)
List<Entry> list = new ArrayList(info.entrySet());
希望这有助于
你也越来越关于不使用泛型不当,从而导致正是那种异常的警告。 – chrylis 2014-12-08 06:27:28
这就是为什么不使用原始类型...如果你不使用原始类型,这甚至不会编译。 – Radiodef 2014-12-08 06:55:16
在Page类中,setInfo方法:增强for循环尝试将this.entry替换为entryList – techGaurdian 2014-12-08 08:33:49