我有一个 MyApplicationClass,其中存放了一个 ArrayList,然后我在 MainActivity 中创建一个变量 ArrayList,并将其分配给 MyApplciationClass 中的变量,最后我调用局部变量的删除来删除一个值,但该值从两个变量中删除MyApplicationClass 和 localvariable,这可能是因为我只是从 MyApplicationClass 检索列表,我没有做任何其他事情?
这是我的代码:
我的应用程序类:
private ArrayList<String> text = new ArrayList<>();
public ArrayList<String> getText() {
return text;
}
public void addTest(String input) {
text.add(input);
}
主要 Activity :
//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);
但是当我调试并查看变量时,我可以看到该值在 teSTLocal 中被正确删除,而且在 MyApplicationClass 中的文本中也被正确删除,但我只想从中删除一个值本地文本。
非常感谢。
最佳答案
这两个变量引用同一个 ArrayList
对象。
此赋值使 teSTLocal
引用 MyApplicationClass
实例的 ArrayList
对象:
ArrayList<String> testlocal = myApplicationClass.getText();
要创建新的 ArrayList
,您必须使用 new
运算符创建新对象:
ArrayList<String> testlocal = new ArrayList<>(myApplicationClass.getText());
现在,删除(甚至添加)这两个 ArrayList 对象中的一个元素将永远不会反射(reflect)在另一个 ArrayList 对象中。
但请注意,new ArrayList(Collection c)
不会对所复制的元素进行深层复制。
因此,修改一个或另一个 ArrayList 对象中的任何元素的状态仍将反射(reflect)在另一个对象中。
在您的实际情况中,这不是问题,因为 List
只存储事实上不可变的 String
值。
关于java - 为什么 "ArrayList.remove"在局部变量和 myApplicationClass 中都被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45842435/