Java坚持要改变这两个变量

时间:2017-12-05 18:09:25

标签: java setter accessor

运行我的MVC模型应用程序时,会创建一个ApplicationModel的Singleton实例。

在我的控制器类中运行main方法时,List<Shop>使用shops分配给setShops()。如果shopsDefault = nullsetShops()也会继续将同一List<Shop>分配给shopsDefault

到目前为止,非常好。

但是,当我致电sortShopsByName()时 - 正如您在下面看到的那样使用setShops() - shopsshopsDefault都会被排序!为什么不按预期排序shops

我的ApplicationModel班级......

import java.util.*;

public class ApplicationModel {

    //static variables
    private static ApplicationModel instance = null;

    //instance variables
    private List<Shop> shops;
    private List<Shop> shopsDefault;

    //constructors
    private ApplicationModel() {}

    //getInstance method
    public static ApplicationModel getInstance() {
        if (instance == null) {
            instance = new ApplicationModel();
        }

        return instance;
    }

    //getters and setters
    public List<Shop> getShops() {
        return shops;
    }

    public void setShops(List<Shop> shops) {
        this.shops = shops;
        if (this.shopsDefault == null) {
            this.shopsDefault = shops;
        }
    }

    public List<Shop> getShopsDefault() {
        return this.shopsDefault;
    }


    //Shop methods
    public void sortShopsByName() {
        List<Shop> shops = this.getShops();
        Collections.sort(shops);
        this.setShops(shops);
    }

    public void returnShopsToDefaultOrder() {

        List<Shop> shopsDefault = this.getShopsDefault();
        setShops(shopsDefault);
    }
}

3 个答案:

答案 0 :(得分:2)

shops分配给shposDefault后,它们都会引用同一个实例。因此,通过两个实例对实例所做的更改将通过两个引用可见。

如果这不是预期的行为,您可以在设置shops时复制null列表。 E.g:

public void setShops(List<Shop> shops) {
    this.shops = shops;
    if (this.shopsDefault == null) {
        this.shopsDefault = new ArrayList<>(shops);
    }
}

答案 1 :(得分:1)

因为它是相同的列表。如果您想要不同的列表,请在将其分配给shopsDefault时进行复制(即new ArrayList<Shop>(shops))。

答案 2 :(得分:1)

在此代码中,您将两个成员都设置为相同的列表引用:

this.shops = shops;
if (this.shopsDefault == null) {
   this.shopsDefault = shops;
}

如果要分开它们,请使用以下内容:

this.shops = shops;
if (this.shopsDefault == null) {
   this.shopsDefault = new ArrayList<Shop>(shops);
}