0

I have an object stored in a global variable let's say:

static ArrayList<Object> list = new ArrayList<Object>();

I want to store it later to look into it without actually changing the values in the structure itself. So I am doing something similar to this:

public void someMethod()
{
     ArrayList<Object> tempList = new ArrayList<Object>();
     tempList = list;
     list.remove(0);
}

I'm thinking this may have something to do with me initializing the variable as "static". I don't usually do that but Eclipse told me I had to so I just let the change happen.

My understanding would be that I am storing the original list into a temporary list and anything I do to the temporary list would be independent of the original list. But it appears that if I were to remove something from this above list, that the original list is removing it as well.

I remember learning that this could happen sometimes but I think I've done this before without having that issue.

I apologize if this is a repeated question but the way I worded it didn't show me an question that was similar.

Thanks!

4

2 回答 2

4

我的理解是我将原始列表存储到一个临时列表中,我对临时列表所做的任何事情都将独立于原始列表。

不是这种情况。当你做类似的事情时

a = b;

然后两者都 a引用b一个对象。a出现突变,b反之亦然(因为只有一个对象有问题)。在这种情况下,您可能希望使用以下的复制构造函数ArrayList

ArrayList<Object> tempList = new ArrayList<Object>(list);

请注意,这里我们显式地创建了一个新的独立对象并将分配给tempList.

请注意,这会创建所谓的浅拷贝:列表本身引用的对象不会被复制,而是会创建一个新列表,其中包含对与原始列表相同的对象的引用。

于 2013-09-17T23:38:27.777 回答
0

在你的结尾someMethod,你tempList消失在 GC 的黑暗虚空中。如果你想保留它,你需要把它变成一个类似的字段list

此外,分配listtempList使您对同一对象有两个引用。

于 2013-09-17T23:38:37.700 回答