問題描述
晚上!
我有以下地圖:
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 中已存在的鍵的列表中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!