我有一个ArrayList,其中一些条目作为HashMap中的值,如何向其中添加新值?

谢谢。是这样的:

Map<String, ArrayList<String>> index = new HashMap<String, ArrayList<String>>();
void add(String kword, String... urls){
    if(index.containsKey(kword)){
        index.get(kword).addAll(Arrays.asList(urls));
    } else {
        index.put(kword, (ArrayList<String>) Arrays.asList(urls));
    }
}

最佳答案

假设您符合以下要求:

Map<K, ArrayList<V>> map = new HashMap<K, ArrayList<V>>();


那么这应该允许您将新值添加到地图中作为值包含的任何列表中:

map.get(listKey).add(newValue);


自然地,您还可以将map.get(listKey)的结果存储到一个临时变量中,以避免在插入多个值时map.get()的开销:

List<V> list = map.get(listKey);

for (V value : newValues)
    list.add(value);

10-02 10:05
查看更多