0
ArrayList<Integer> list1= new ArrayList<>();
ArrayList<Integer> list2= new ArrayList<>();
for(int i=1;i<=5;i++){
list1.add(i);
}
System.out.println("List1 "+list1);
list2=list1;
System.out.println("List2 "+list2 );
list2.add(6);
System.out.println("List1 Changed "+list1 );

Output :

List1 [1, 2, 3, 4, 5]
List2 [1, 2, 3, 4, 5]
List1 Changed [1, 2, 3, 4, 5, 6]

I know on using list2=list1, and on changing list2, list1 also will get altered. But I dont want my list1 to get it changed. I have to use list2=list1, but is there any way I get the List1 [1, 2, 3, 4, 5] only ?

Aditya
  • 21
  • 1

5 Answers5

3

If you want list2 to reference a different List than list1, make a copy:

Change

list2=list1;

to

list2 = new ArrayList<>(list1);

Note that since you are overwriting the reference to the original List referenced by list2, there's no need to create it in the first place:

ArrayList<Integer> list1 = new ArrayList<>();
for(int i = 1; i <= 5; i++) {
    list1.add(i);
}
System.out.println("List1 "+list1);
ArrayList<Integer> list2 = new ArrayList<>(list1);
System.out.println("List2 "+list2);
list2.add(6);
System.out.println("List1 Not Changed "+list1);
Eran
  • 387,369
  • 54
  • 702
  • 768
  • There is a method to do the same instead of creating new Object. – Suresh Atta Mar 08 '18 at 07:43
  • @ꜱᴜʀᴇꜱʜᴀᴛᴛᴀ yes there is, but that statement is also meant to replace the `ArrayList list2= new ArrayList<>();` statement. – Eran Mar 08 '18 at 07:44
1
list2=list1;

You are overriding list2 with list1 reference. If you want to keep them separate, just add them and don't assign

list2.addAll(list1);
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You can copy the list instead of just assigning a reference to it:

list2 = new ArrayList<>(list1);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

list1 and list2 are variables that are both a reference to an object which is of type ArrayList<Integer>. They have exactly the same value after list2 = list1 is executed, this value is an address of an object, NOT the object itself. This means that at the point you lost the original list that list2 was pointing to and you have two variables pointing to the same place in the memory.

What you can do to keep two independent lists is add elements from list1 to list2, like this

List<Integer> list2 = new ArrayList<>(list1);

or this:

List<Integer> list2 = new ArrayList<>();
/*code inbetween*/
list2.addAll(list1);
Yoda
  • 17,363
  • 67
  • 204
  • 344
0
    ArrayList<Integer> list1= new ArrayList<>();
    ArrayList<Integer> list2= new ArrayList<>();
    for(int i=1;i<=5;i++){
    list1.add(i);
    }
    System.out.println("List1 "+list1);
    list2=(ArrayList<Integer>) list1.clone();
    System.out.println("List2 "+list2 );
    list2.add(6);
    System.out.println("List1 Changed "+list1 );