使用this.put(“String”, “String”)方法添加一个键值对。但是,它会覆盖现有值,而我想使用同一个键存储和配对多个值。
使用可以存储多个对象的ArrayList,当为HashMap分配一个值(例如,称为myHashMap)时,首先检查该键之前是否已使用过,如果尚未使用过,则可以创建一个具有要添加值的新ArrayList(如果有的话),则只需将值添加到列表中即可。
假设key和value具有所需的值:
ArrayList<String> list;
if(myHashMap.containsKey(key)){
// if the key has already been used,
// we'll just grab the array list and add the value to it
list = myHashMap.get(key);
list.add(value);
} else {
// if the key hasn't been used yet,
// we'll create a new ArrayList object, add the value
// and put it in the array list with the new key
list = new ArrayList<String>();
list.add(value);
myHashMap.put(key, list);
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有