1

I have a MyApplicationClass into which I stock An ArrayList, then I create a variable ArrayList in my MainActivity and assign it the variable in MyApplciationClass and finally I call remove to the local variable to remove a value but the value is removed from both MyApplicationClass and the localvariable and it can be possible because I just retrieve the list from MyApplicationClass I didin't make anything else ?

Here is my code:

MyApplicationClass:

private ArrayList<String> text = new ArrayList<>();


public ArrayList<String> getText() {
    return text;
}

public void addTest(String input) {
    text.add(input);
}

MainActivity:

//When click on a button:

final MyApplicationClass myApplicationClass = (MyApplicationClass) getApplicationContext();

//I add some example values
myApplicationClass.addTest("1");
myApplicationClass.addTest("2");

//Here I retrieve the variable in MyApplicationClass to put in into a local variable:

ArrayList<String> testlocal = myApplicationClass.getText();

//And here I remove a value from the localvariable testlocal:
test.remove(1);

But when I debug and see variable I can see that the value is correctly deleted in testlocal but too in text in MyApplicationClass but I just want to remove a value from textlocal.

Thanks a lot.

Melvin Auvray
  • 57
  • 1
  • 7

2 Answers2

5

The two variables refers to the same ArrayList object.

This assignment makes testlocal refers to the ArrayList object of the MyApplicationClass instance :

ArrayList<String> testlocal = myApplicationClass.getText();

To create a new ArrayList, you have to create a new object by using the new operator :

ArrayList<String> testlocal = new ArrayList<>(myApplicationClass.getText());

Now removing (or even adding) one element in any of these two ArrayList objects will never be reflected in the other ArrayList object.

But note that new ArrayList(Collection c) will not make a deep copy of the elements copied.
So modifying the state of any element in one or the other ArrayList object will be still reflected in the other.
In your actual case, it is not a problem as the Lists store only String values that are de facto immutable.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
1

You need to create a copy of the original list. Also, generally it's better to depend on the List interface instead of the ArrayList class.

You can create the copy in the getText() method. This is easy because you need to modify the code on only one place. On the other hand, no outer class will be able to change your MyApplicationClass:

public List<String> getText() {
    return new ArrayList<>(text);
}

Alternatively, you can create a local copy whenever you retrieve it:

List<String> testlocal = new ArrayList<>(myApplicationClass.getText());
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49