這完全是因爲java中的標準Map實現只存儲單對(oneKey,oneValue)。在Java標準Map中爲特定鍵存儲多個值的唯一方法是將「collection」存儲爲值,然後您需要通過鍵訪問該集合(從Map),然後使用該集合「value」作爲常規集合,在你的例子中作爲ArrayList。所以你不要直接通過map.put(除了創建空集合)放置某些東西,而是通過鍵取得整個集合並使用這個集合。
你需要像Multimap之,例如:
public class Multimap<T,S> {
Map<T, ArrayList<S>> map2 = new HashMap<T, ArrayList<S>>();
public void add(T key, S value) {
ArrayList<T> currentValuesForGivenKey = get(key);
if (currentValuesForGivenKey == null) {
currentValuesForGivenKey = new ArrayList<T>();
map2.get(key, currentValuesForGivenKey);
}
currentValuesForGivenKey.add(value);
}
public ArrayList<S> get(T key) {
ArrayList<String> currentValuesForGivenKey = map2.get(key);
if (currentValuesForGivenKey == null) {
currentValuesForGivenKey = new ArrayList<S>();
map2.get(key, currentValuesForGivenKey);
}
return currentValuesForGivenKey;
}
}
那麼你可以使用它像這樣:
Multimap<String,String> map2 = new Multimap<String,String>();
map2.add("1","2");
map2.add("1","3");
map2.add("1","4");
for (String value: map2.get("1")) {
System.out.println(value);
}
會打印:
2
3
4
地圖列表是好的事情,但它不清楚你想要做什麼 – AndreyS