【问题标题】:How to pass HashMap value to list如何将 HashMap 值传递给列表
【发布时间】:2015-02-05 18:49:03
【问题描述】:

如何将 hashmap 值传递给 List 条目是字符串键值类型?

页面类:

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

【问题讨论】:

  • 您还会收到有关未正确使用泛型的警告,这正是导致此类异常的原因。
  • 这就是为什么不使用原始类型...如果您不使用原始类型,这甚至不会编译。
  • 在Page类中,setInfo方法:增强for循环尝试将this.entry替换为entryList

标签: java list map hashmap


【解决方案1】:

public void setInfo(final List&lt;Entry&gt; entryList) 的方法中,您需要List&lt;Entry&gt; 的类型,同时传递List&lt;String&gt; 的类型。

如果您不熟悉 Generic,请查看here 了解更多信息。

因此,对于您的情况,您需要在 List 中添加一个 Entry 类型。方法 Map#entrySet() 可以做到这一点,它返回 Map.Entry 的集合。

您可以使用这样的条目集创建列表:

   List<Entry> list = new ArrayList(info.entrySet());

【讨论】:

  • 如果你需要一个Entry类型在你的list里面,你需要从你的map中获取entry的集合。方法entrySet()可以做到这一点,它返回一个Map.Entry的集合。
  • List list = new ArrayList(info.entrySet()); page.setEntry(list);
  • 我试过这个.. 但在 setInfo. this.prop.put(objEntry.getKey(), objEntry.getValue());-- 我得到了 null
  • @pals ,所以异常的问题解决了。您正在循环 this.entry,并且您从不使用 List entryList 的 pass 参数。尝试将其替换到传递的列表中,或在循环之前使用this.entry= entryList
【解决方案2】:

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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    相关资源
    最近更新 更多