0

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.

  • I'm assuming that `a1.get(0)` (the first iteration) is referencing `a`, and then calling `add(0)` will add an element to `a`. The reason is that `List` is an object, and is passed around as a reference. – Ryan Dougherty Aug 06 '14 at 15:02
  • 1
    possible duplicate of [How to copy a java.util.List into another java.util.List](http://stackoverflow.com/questions/14319732/how-to-copy-a-java-util-list-into-another-java-util-list) – jny Aug 06 '14 at 15:05
  • @Ryan So is there any possible solution to make `a` unchangeable. If `a` and `a1` are `List` instead of `List>`, then the element adding of `a1` will not change the element of `a`. Why is it – user3207822 Aug 06 '14 at 15:14
  • @user3207822 You can use this: http://stackoverflow.com/a/6536128/3232207 to copy out `a1.get(0)`, i.e.: `List b1 = new ArrayList(a1.get(0));` – Ryan Dougherty Aug 06 '14 at 15:15

2 Answers2

0

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()); 
Rika
  • 768
  • 1
  • 5
  • 16
0

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

John Davidson
  • 36
  • 1
  • 3