Java 集合数组

Java collections array

如何在 Java 中创建集合数组?例如在 c++ 中我们有:

vector <int> adj[10]; 

然后使用for循环初始化它:

 cin >> nodes;
 cin >> edges;

 for(int i = 0;i < edges;++i) {
  cin >> x >> y;
  adj[x].push_back(y);                   
  adj[y].push_back(x);                   
}

例如:

6  
4  
1 2  
2 3  
1 3  
4 5   

以上输入adj如下:

索引

0   -  
1   -   2   3  
2   -   1   3  
3   -   2   1  
4   -   5  
5   -   4  
6   -  
7   -  

这是一个 java 版本的 C++ 代码:

public static void main(String[] args) {

    ArrayList<Integer>[] adj = new ArrayList[10];

    for (int i = 0; i < adj.length; i++)
        adj[i] = new ArrayList<>();

    Scanner in = new Scanner(System.in);

    int nodes = in.nextInt();
    int edges = in.nextInt();

    for (int i = 0; i < edges; ++i) {
        int x = in.nextInt();
        int y = in.nextInt();
        adj[x].add(y);
        adj[y].add(x);
    }

    for (int i = 0; i < adj.length; i++)
        System.out.println(adj[i]);

}