如何在java中实现map[u].push_back(v) (c++)

How to do map[u].push_back(v) (c++) in java?

本文关键字:push back c++ java 实现 map      更新时间:2023-10-16

在c++中,如果我像map< int ,vector < int > > m;这样声明map STL,我可以在m[u].push_back(v);中以这种方式使用它。但是如何在Java中做到这一点呢?

就像这样,

public static void main(String[] args) {
    int u = 0;
    int v = 1;
    Map<Integer, ArrayList<Integer>> map = 
        new HashMap<Integer, ArrayList<Integer>>();
    if (map.get(u) == null) { // Add a List if they key is null.
        map.put(u, new ArrayList<Integer>());
    }
    // Add v to the List at u.
    map.get(u).add(v);
    System.out.println(map);
}

如果我理解你的问题,这应该是你正在寻找的。

Map<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>();
map.put(0, new ArrayList<Integer>());
Integer someInt = 1;
map.get(0).add(someInt); //get arraylist and add to back.