如何在HashMap中的ArrayList中添加元素 [英] How to add element into ArrayList in HashMap

查看:260
本文介绍了如何在HashMap中的ArrayList中添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  HashMap< String,ArrayList&Item>> Items = new HashMap< String,ArrayList< Item>>(); 


解决方案

  HashMap< String,ArrayList< Item>> items = new HashMap< String,ArrayList< Item>>(); 

public synchronized void addToList(String mapKey,Item myItem){
列表< Item> itemsList = items.get(mapKey);

//如果列表不存在创建它
if(itemsList == null){
itemsList = new ArrayList< Item>();
itemsList.add(myItem);
items.put(mapKey,itemsList);
} else {
//如果项目不在列表
中,则添加if(!itemsList.contains(myItem))itemsList.add(myItem);
}
}


How to add element into ArrayList in HashMap?

    HashMap<String, ArrayList<Item>> Items = new HashMap<String, ArrayList<Item>>();

解决方案

HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();

public synchronized void addToList(String mapKey, Item myItem) {
    List<Item> itemsList = items.get(mapKey);

    // if list does not exist create it
    if(itemsList == null) {
         itemsList = new ArrayList<Item>();
         itemsList.add(myItem);
         items.put(mapKey, itemsList);
    } else {
        // add if item is not already in list
        if(!itemsList.contains(myItem)) itemsList.add(myItem);
    }
}

这篇关于如何在HashMap中的ArrayList中添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆