1

If I create a list and add ten elements then copy the list object to another and call list.clear on the second list, both of the lists are cleared.

Random random = new Random();
List<Double> list1 = new ArrayList<Double>();
List<Double> list2 = new ArrayList<Double>();

for (int i = 0; i < 10; i++) {
    list1.add(random.nextDouble());
}

list2 = list1; //Both lists have ten elements

list1.clear(); //Both lists are now empty

Is this normal? Am I missing something? If I iterate through the first list and add the elements one by one this does not occur, only with the list2 = list1 line.

braX
  • 11,506
  • 5
  • 20
  • 33
  • 1
    possible duplicate of [How do I copy the contents of one ArrayList into another?](http://stackoverflow.com/questions/8441664/how-do-i-copy-the-contents-of-one-arraylist-into-another) – m0skit0 Jul 20 '15 at 17:31

3 Answers3

5
list2 = list1; //Both lists have ten elements

This doesn't copy list1 to list2. It makes the variable list2 refer to the same list as list1. Both variables point at the same list object.

Before

list1 -----> [ArrayList #1]

list2 -----> [ArrayList #2]

After

list1 --+--> [ArrayList #1]
        |
list2 --+    [ArrayList #2]   (orphaned, will be garbage collected)

To copy the elements of the first list to the second, instead do:

list2.addAll(list1);

(If list2 weren't empty you would also need list2.clear().)

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
2
list2 = list1;

This doesn't copy list1 to list2, but makes list2 reference (point to) list1. Since both list1 and list2 now point to the same list, it doesn't matter if you use list1 or list2 since both will be acting on the same list.

If you want to copy it, do (after adding the elements):

final List<Double> list2 = new ArrayList<Double>(list1);

This also means that List<Double> list2 = new ArrayList<Double>() is superfluous.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
1

I think it's because both lists are pointing to the same value in memory. Just populate the list with a foreach loop.

Bryan Mudge
  • 432
  • 4
  • 12
  • 1
    Instead of a `foreach`, one should use [`addAll(Collection extends E> c)`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#addAll-java.util.Collection-). This can be more performant. – Turing85 Jul 20 '15 at 19:30