为什么静态访问列表会更新,即使我们将其分配给本地

时间:2013-10-08 14:08:19

标签: java

public static void Method1(String a)
{
    List<DataBean> list = new ArrayList<DataBean>();
    list = StaticClass.masterList; // it has prepopulated list item


    for (JavaBean bean: list) {
        //Some condition and we call bean.setters 

    }

}

为什么StaticClass.masterList在for循环中得到更新我虽然调用了bean的更新?

2 个答案:

答案 0 :(得分:2)

对列表的引用是您要复制的内容,但不会更新。

可以在它引用的对象中更新什么。

注意:

List<DataBean> list = new ArrayList<DataBean>();

此处list不是List,它只是对列表的引用,这就是您可以将其分配给新对象的原因。

如果你想获取masterList的浅表副本,你可以这样做。

List<DataBean> list = new ArrayList<DataBean>(StaticClass.masterList);

这样,如果更改列表,则不会更改主列表。但是,如果您更改其中一个DataBeans,则会显示此信息。如果您需要深层复印,可以

List<DataBean> list = new ArrayList<DataBean>();
for (DataBean db: StaticClass.masterList)
     list.add(new DataBean(db));

答案 1 :(得分:2)

因为listStaticClass.masterList会引用同一个对象。

因此,如果您在list中的任何对象上调用setter,您也会在StaticClass.masterList中看到更改。