简体   繁体   English

按值发送二维数组列表

[英]Send 2D Arraylist by value

I m trying to send a 2D Arraylist by value So I wrote the following code 我试图通过值发送2D Arraylist,所以我写了以下代码

    public static void main(String[] args) {
        ArrayList<List<Object>> a = new ArrayList<List<Object>>();

        for (int i = 0; i < 10; i++) {
            List in_a =  Arrays.asList("aa","bb","cc","dd");
            a.add(in_a);
        }

// THE FOLLOWING WOULD WORK IN A 1D ARRAY, BUT NOT 2D
//        ArrayList<List<Object>>  b = new ArrayList < List<Object> > (a);

// THIS IS MY WORKING SOLUTION
        ArrayList < List<Object> > b = new ArrayList < List<Object> >() ;
        for (int i = 0; i < a.size(); i++) {
            List in_b =  new ArrayList(a.get(i));
            b.add(in_b);
        }

        b.get(1).set( 3, "33");

        System.out.println("a.get(1).get(3) = " + a.get(1).get(3));
        System.out.println("b.get(1).get(3) = " + b.get(1).get(3));
    }

However I do not like this solution 但是我不喜欢这个解决方案

is there a better way to solve this issue? 有没有更好的方法来解决此问题?

Since Lists can only contain Objects or classes that extend Object (all of them) you will forcibly copy only the reference into your new list. 由于列表只能包含Objects或扩展Object类(全部),因此您将仅将引用复制到新列表中。 So if you want a 1:1 copy of a "2D-List", you need to loop through the "first dimension" and copy the "second dimension": 因此,如果您想要“ 2D列表”的1:1副本,则需要遍历“第一维”并复制“第二维”:

ArrayList<List<Object>> c = new ArrayList<>();
for(List in_a : a){
    c.add(new ArrayList<>(in_a));
}

This is just a shorter version from what you already did in your loops. 这只是您在循环中所做的工作的简短版本。 So we create a new ArrayList c and fill it with a copy of each sub-list from a . 所以我们创建了一个新ArrayList c ,并从每个子列表的副本填充a But be aware that here I use the enhanced loop (without index), so there is no guarantee that c is in the same order as a (although quite frankly, you should be fine) 但是请注意,这里我使用增强的循环(不带索引),因此不能保证ca顺序相同(尽管坦白地说,您应该没问题)

You can try using clone() method: 您可以尝试使用clone()方法:

ArrayList <List<Object>> originalList = new ArrayList <List<Object>>();
// ...
ArrayList <List<Object>> list2D = new ArrayList <List<Object>>();
for (List<Object> list : originalList) {
    list2D.add(list.clone());
}

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

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