[英]ArrayList<String> Object assignment
I have two separate objects ArrayList<String>
in two separate packages Top and top10. 我在两个单独的包Top和top10中有两个单独的对象ArrayList<String>
。 I assign the value of top10 to Top in my activity. 我在活动中将top10的值指定为Top。 And now if I remove an element from Top it also gets removed from top10. 现在如果我从Top中删除一个元素,它也会从top10中删除。 I don't know why is this happening? 我不知道为什么会这样? I feel totally dumbfounded. 我觉得完全傻眼了。 Is there something I don't know about java? 有什么我不知道的关于Java的东西吗? Or is it android? 还是android?
This is my activity code: 这是我的活动代码:
ArrayList<String> Top = new ArrayList<String>();
// ServiceCall is the name of the class where top10 is initialized.
Top = ServiceCall.top10;
System.out.println("top WR: "+ServiceCall.top10);
if(Top.get(0).equals("Please Select")) Top.remove(0);
System.out.println("top WR: "+ServiceCall.top10);
The second printed out statement has one element less than the one before. 第二个打印出来的语句有一个元素少于前一个元素。
You are pointing to the same Object. 您指向同一个对象。
Top = ServiceCall.top10;
is not creating a new Object, but making a reference to the other one, hence all changes in both pointers will be reflected in the same Object. 不创建新的Object,而是引用另一个,因此两个指针中的所有更改都将反映在同一个Object中。
You'll have to create a new one passing the other one as parameter: 你必须创建一个新的传递另一个作为参数:
List<String> Top = new ArrayList<String>(ServiceCall.top10);
You are pointing Top to top10, not creating a new list (your initializer is effectively unused right now, as you are just repointing it to the other list.) 您将Top指向top10,而不是创建新列表(您的初始化程序现在实际上未被使用,因为您只是将其重新分配到其他列表。)
You should do: 你应该做:
ArrayList<String> Top = new ArrayList<String>(ServiceCall.top10);
This will create a shallow copy. 这将创建一个浅表副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.