简体   繁体   中英

java arraylist of arraylist copy

I have code as follows:

    //Assume a has one arrayList in it
    List<List<Integer>> a1 = new ArrayList<List<Integer>>(a);

    for(int i=0;i<1;i++){
        List<Integer> b1 = a1.get(i);
        b1.add(0);
    }

    System.out.println(a.toString()); //now there are 2 elements in arraylist a

I thought the above code make change only on a1 . But the print out result shows that both arraylist a1 and a are changed. How can I make only a1 change without a changed as well.

Except putting this:

List<List<Integer>> a1 = new ArrayList<List<Integer>>(a);

Do this instead:

a1.addAll(a);

So have:

List a = new ArrayList();
a.add("Hello");
a.add("World"); 
List a1 = new ArrayList();
a1.addAll(a);
a1.add("GoodBye");
System.out.println(a.toString()); 

I think there's a slight misunderstanding in how your code is structured when you refer to "making a change". The following line:

 List<Integer> b1 = a1.get(i);

Is, in other words:

"b1 is a List of Integers which is located in memory at the same place as the List of integers located at index i of a1".

So, b1 now references the List of integers at index i in a1 (which is the List at index 0 based on your loop, which would be the same list referenced by variable a ).

When you write:

b1.add(0);

You are adding the integer 0 to the List of integers referenced by both a and b1 . So, you are inherently changing what is in a , and in the process, changing the value of something held by a1 as well.

I'm not sure exactly what you need when you say you need to modify a1 and not a - do you need to add a new List of integers to the List? In that case, you can simply do a a1.add(NewList) , where NewList is a List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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