问题描述
晚上!
我有以下地图:
HashMap<String, ArrayList> myMap = new HashMap<String, ArrayList>();
然后我向其中添加了以下数据:
I then added the following data to it:
ArrayList myList = new ArrayList();
myList.add("Test 1");
myList.add("Test 2");
myList.add("Test 3");
myMap.put("Tests", myList);
这给我留下了以下数据:
This left me with the following data:
关键:测试
值:测试 1、测试 2、测试 3
Values: Test 1, Test 2, Test 3
我的问题是,如何在我已经存在的键上添加新值?例如,如何将值Test 4"添加到我的键Tests"中.
My question is, how do I then add new values on to my already existing key? So for example, how could I add the value "Test 4" onto my key "Tests".
谢谢.
推荐答案
只需从地图中获取列表,然后将元素添加到列表中:
Simply get the list from the map and then add the element to the list:
ArrayList list = myMap.get("Tests");
list.add("Test4");
对于您的代码,还有其他一些需要注意的地方.首先,不要使用原始的输入 ArrayList
.使用泛型:
There are some other things that can be remarked about your code. First of all, don't use the raw type ArrayList
. Use generics:
HashMap<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
ArrayList<String> myList = new ArrayList<String>();
myList.add("Test 1");
myList.add("Test 2");
myList.add("Test 3");
myMap.put("Tests", myList);
第二,程序到接口,而不是实现.换句话说,程序使用接口Map
和List
而不是实现HashMap
和ArrayList
.这是众所周知的 OO 编程原则,例如,如果需要,可以更轻松地切换到不同的实现.
Second, program to interfaces, not implementations. In other words, program using interfaces Map
and List
rather than the implementations HashMap
and ArrayList
. This is a well-known OO programming principle, which makes it for example easier to switch to a different implementation, if necessary.
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
List<String> myList = new ArrayList<String>();
myList.add("Test 1");
myList.add("Test 2");
myList.add("Test 3");
myMap.put("Tests", myList);
最后,语法提示:如果您使用的是 Java 7 或更新版本,则可以使用 <>
并且不必重复类型参数:
Finally, a syntax tip: if you're using Java 7 or newer you can use <>
and you don't have to repeat the type arguments:
Map<String, List<String>> myMap = new HashMap<>();
List<String> myList = new ArrayList<>();
myList.add("Test 1");
myList.add("Test 2");
myList.add("Test 3");
myMap.put("Tests", myList);
myMap.get("Tests").add("Test 4");
这篇关于将值添加到 Map 中已存在的键的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!