使用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<String> 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);
}
原文地址:https://cloud.tencent.com/developer/article/2181127
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。