0

I'm setting a temporary ArrayList equal to a pre-established ArrayList. Changes to the temporary ArrayList seem to also transfer over to the pre-established one. Why does this occur and how can I keep the pre-established ArrayList unchanged?

I know that this phenomenon does not occur in situations that involve ints.

ArrayList<Integer> array = new ArrayList<>();

for (int i = 0; i < 3; i++){
    array.add(i);
}

ArrayList<Integer> tempArr = array;
tempArr.remove(0);

I expect array to be [0,1,2], but I get [1,2]. I would like the output to be array = [0,1,2] and tempArr = [1,2].

2 Answers2

0

You just copied the reference of the list to the new variable. That means you have 2 references array and tempArr that are pointing to the same object. You could create a new ArrayList from the old one:

ArrayList<Integer> tempArr = new ArrayList<>(array);
Ruslan
  • 6,090
  • 1
  • 21
  • 36
0

Variables array and tempArr booth point to same instance of ArrayList<Integer> object, hence modifying one will make changes to other.

What you need is to create new instance and then transfer all elements to it:

ArrayList<Integer> array = new ArrayList<>();

for (int i = 0; i < 3; i++){
    array.add(i);
}

ArrayList<Integer> tempArr = new Arraylist<>();
tempArr.addAll(array);
tempArr.remove(0);

This code can also be simplified since Arraylist<> is offering you constructor that will add elements from another collection:

ArrayList<Integer> tempArr = new Arraylist<>(array);
tempArr.remove(0);