0

I am trying to make a list be a direct copy of another. Would this work?

list1 = list2

Would it transfer all contents or nothing at all?

4 Answers4

1

You are not making a copy, you are adding a reference. Both making an additional reference and inserting items into a list are atomic. A procedure is atomic if it is not splittable. Either it is completely done or not.

See also the following thread on how to correctly clone a list. Java Collections copy list - I don't understand

Googling for the java clone method will enlighten you too.

Community
  • 1
  • 1
poitroae
  • 21,129
  • 10
  • 63
  • 81
0

It won't. Cloning objects in java is not so stright forward, see the link How do I copy an object in Java?

Community
  • 1
  • 1
anoopelias
  • 9,240
  • 7
  • 26
  • 39
0

No. It will only make list2 reference point to the same list that is stored in list1 reference. You can use copy constructor to copy references from one list to another, but be careful since this is not deep copy -> new list will contain exactly the same objects that are stored in original list. Here is example

List<String> list1 = new ArrayList<>();
list1.add("one");
list1.add("two");

List<String> list2 = list1;//now list2 will point to the same list as list1
list2.add("A");

//lets print content of list1
System.out.println(list1); // -> output: [one, two, A]

//--------------------------------------------------------------

//This way you can create separate list that contains same values as list1
List<String> list3 = new ArrayList(list1);
list3.add("B");

System.out.println(list1); // -> output: [one, two, A]
System.out.println(list3); // -> output: [one, two, A, B]
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

Using a direct assignment is not useful in most cases. It just as if you have the exact same variable with two different names as both pointing to the same memory address.

If you want to clone a list into another you should use a copy constructor

e.g.

ArrayList<E> copyList = new ArrayList<E>(originalList);
iTech
  • 18,192
  • 4
  • 57
  • 80