ArrayList <string>对象赋值</string>

时间:2012-07-25 17:45:05

标签: java android

我在两个单独的包Top和top10中有两个单独的对象ArrayList<String>。我在活动中将top10的值指定为Top。现在如果我从Top中删除一个元素,它也会从top10中删除。我不知道为什么会这样?我觉得完全傻眼了。有什么我不知道的关于Java的东西吗?还是android?

这是我的活动代码:

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);

第二个打印出来的语句有一个元素少于前一个元素。

2 个答案:

答案 0 :(得分:2)

您指向同一个对象。

Top = ServiceCall.top10;

不创建新的Object,而是引用另一个,因此两个指针中的所有更改都将反映在同一个Object中。

你必须创建一个新的传递另一个作为参数:

List<String> Top = new ArrayList<String>(ServiceCall.top10);

答案 1 :(得分:1)

您指向Top10,而不是创建新列表(您的初始化程序现在实际上未被使用,因为您只是将其重新分配到其他列表。)

你应该这样做:

ArrayList<String> Top = new ArrayList<String>(ServiceCall.top10);    

这将创建一个浅表副本。