这完全是因为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