简体   繁体   English

添加元素时Arraylist的Arraylist问题

[英]Arraylist of Arraylist problem in adding elements

I'm trying to do something equivalent to the following C++ code:我正在尝试做一些与以下 C++ 代码等效的事情:

vector <vector<int> > adjlist;
adjlist.resize(maxv+1);
adjlist[n1].push_back(n2);

Where n1,n2 are integers, I've googled a lot and found that Arraylists are the closest match in Java so I tried the following:其中 n1,n2 是整数,我用谷歌搜索了很多,发现 Arraylists 是 Java 中最接近的匹配,所以我尝试了以下方法:

List<List<Integer> > adjlist =  new ArrayList<List<Integer> >(maxv);
adjlist.get(n1).add(n2);

but it's not working at all, I know I can build another arraylist let's name it al then the following would work:但它根本不起作用,我知道我可以构建另一个数组列表,让我们将其命名为al然后以下将起作用:

adjlist.add(al);

but that won't work for me, I need to add individual integers as I mentioned, any help?但这对我不起作用,我需要添加我提到的单个整数,有什么帮助吗?

int n = 5;整数 n = 5;

    List<List<Integer> > list =  new ArrayList<List<Integer> >(n);
    for(int i=0;i<n;i++)
    {
        list.add(new ArrayList<Integer>());
    }

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<10;j++)
        {
            list.get(i).add(j);
        }
    }
    System.out.println(list);

Keep in mind that you can always add something to an Object which itself has been added to something as long as you retain the Object reference .请记住,只要您保留Object reference ,您始终可以向本身已添加到某些内容的Object添加某些内容。 In this case, the object is an ArrayList .在这种情况下,对象是一个ArrayList So you can do the following:因此,您可以执行以下操作:


    int n = 5;
    List<List<Integer>> lists = new ArrayList<>();
    int m = 10;
    for (int i = 0; i < n; i++) {
        List<Integer> temp = new ArrayList<>();
        lists.add(temp);
        for (int j = 0; j < 10; j++) {
            temp.add(j * m);
        }
        m *= 10;
    }

Now print them.现在打印它们。

    for (List<Integer> lst : lists) {
        System.out.println(lst);
    }

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90] [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
[0, 100, 200, 300, 400, 500, 600, 700, 800, 900] [0, 100, 200, 300, 400, 500, 600, 700, 800, 900]
[0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000] [0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000]
[0, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000] [0, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000]
[0, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000] [0, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000]

Note that I added a multiplier m to show that each list is different.请注意,我添加了一个乘数m以显示每个列表都不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM