java - 为什么 "ArrayList.remove"在局部变量和 myApplicationClass 中都被删除?

标签 java android arraylist

我有一个 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/

相关文章:

java - 泛型可以作为复合组件属性标签的 "type"吗?

android - 从数据库获取详细信息时无法创建布局

java - 面向对象与线性编程

Android-(Firebase)如何以不同方式设置 ArrayList 的结构?

java - Java中的字符串...参数

java - 密码与正则表达式匹配

java - 在java中解析JSON响应以提取值

android - 将 wsdl 1.2 与 ksoap2-android 一起使用

android - 应用程序设计在图形中与模拟器中的实际位置

java - 使用 toString 方法和 foreach 循环打印对象时返回什么?