为什么“ArrayList.remove”同时在局部变量和 myApplicationClass 中删除?

Mel*_*ray 1 java android arraylist

我有一个 MyApplicationClass,我在其中存有一个 ArrayList,然后我在 MainActivity 中创建了一个变量 ArrayList 并将 MyApplciationClass 中的变量分配给它,最后我调用了局部变量的 remove 来删除一个值,但该值从 MyApplicationClass 和localvariable,这是可能的,因为我只是从 MyApplicationClass 检索列表我没有做任何其他事情?

这是我的代码:

我的应用程序类:

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


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

public void addTest(String input) {
    text.add(input);
}
Run Code Online (Sandbox Code Playgroud)

主要活动:

//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);
Run Code Online (Sandbox Code Playgroud)

但是当我调试并查看变量时,我可以看到该值在testlocal 中被正确删除,但也在MyApplicationClass中的文本中被正确删除,但我只想从textlocal 中删除一个值。

非常感谢。

dav*_*xxx 5

这两个变量指向同一个ArrayList对象。

这个赋值是testlocal指实例的ArrayList对象MyApplicationClass

ArrayList<String> testlocal = myApplicationClass.getText();
Run Code Online (Sandbox Code Playgroud)

要创建ArrayList新对象,您必须使用new运算符创建一个新对象:

ArrayList<String> testlocal = new ArrayList<>(myApplicationClass.getText());
Run Code Online (Sandbox Code Playgroud)

现在在这两个ArrayList对象中的任何一个中删除(甚至添加)一个元素将永远不会反映在另一个ArrayList对象中。

但请注意, newArrayList(Collection c)不会对复制的元素进行深层复制。
因此,修改一个或另一个ArrayList对象中任何元素的状态仍将反映在另一个对象中。
在您的实际情况中,这不是问题,因为Lists 仅存储String事实上不可变的值。