【问题标题】:How to add an item to list inner hashmap?如何将项目添加到列表内部哈希图?
【发布时间】:2019-11-28 10:09:40
【问题描述】:
HashMap<String, List<Person.Personal>> hashMap = new HashMap();

var attachment = new Person.Personal(name, surname, birthDate);

我需要使用来自另一个地图的键添加项目。

然后我需要如下代码;

if(hashMap.containsKey(courseGroup.getKey().get(0)))
{
    hashMap.put(courseGroup.getKey().get(0), attachment);
}
else
{
    hashMap.put(courseGroup.getKey().get(0), new Arraylist<Person.Personal> (attachment));
}

此代码显示错误: 无法解析构造函数 'Arraylist(Person.Personal)'

如果hashmap有key则添加它的value列表“attachment”,如果没有,创建一个list然后添加“attachment”,我需要。

【问题讨论】:

  • 这里到底有什么问题?
  • 查看Map的方法getOrDefault
  • attachment POJO 还是ArrayList
  • 问题已编辑:此代码显示错误:无法解析构造函数 'Arraylist(Person.Personal)'

标签: java arraylist hashmap


【解决方案1】:
if(hashMap.containsKey(courseGroup.getKey().get(0)))
{
    hashMap.get(courseGroup.getKey().get(0)).add(attachment);
}
else
{
    List<Person.Personal> list = new ArrayList<>();
    list.add(attachment);
    hashMap.put(courseGroup.getKey().get(0), list);
}

这些行解决了我的问题。

【讨论】:

    【解决方案2】:

    由于数组列表已经存在而不是再次使用更新数组列表。

    例如:

    if(hashMap.containsKey(courseGroup.getKey().get(0)))
    {
        // adding values directly to the arraylist.
        hashMap.get(courseGroup.getKey().get(0)).add(attachment);
    }
    else
    {
    
        List<Person.Personal> list= new Arraylist<> ();
        list.add(attachment);
    
        // create a new array and put it there.
        hashMap.put(courseGroup.getKey().get(0), list);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 2020-12-28
      • 2020-04-19
      • 2011-06-21
      相关资源
      最近更新 更多