全局变量在更新时附加多个数据副本

时间:2019-07-20 09:18:27

标签: java android

我创建了一个名为“ Global Services”的类,该类用于全局保存数据并在其他活动中访问它们。但是,当我调用set()方法时,不是概述现有数据,而是附加该数据。下面是我的代码。

我什至尝试删除该实例,但仍然在添加新数据而不是覆盖。

import java.util.ArrayList;
import java.util.List;

public class GlobalServices {
    private static GlobalServices instance;
    String partner, leadsResponse;
    List<Leads> assignedList = new ArrayList<>();
    List<Leads> unAssignedList = new ArrayList<>();
    List<Inventory> listInventory = new ArrayList<>();

    private GlobalServices() {}

    public static GlobalServices getInstance() {
        if (instance == null) {
            instance = new GlobalServices();
        }
        return instance;
    }

    public static void destory() {
        instance = null;
    }

    public String getPartner() {
        return partner;
    }

    public String getLeadsResponse() {
        return leadsResponse;
    }

    public List<Leads> getAssignedList() {
        return assignedList;
    }

    public List<Leads> getUnAssignedList() {
        return unAssignedList;
    }

    public List<Inventory> getListInventory() {
        return listInventory;
    }

    public void setPartner(String partner) {
        this.partner = partner;
    }

    public void setLeadsResponse(String leadsResponse) {
        this.leadsResponse = leadsResponse;
    }

    public void setAssignedList(List<Leads> assignedList) {
        this.assignedList = assignedList;
    }

    public void setUnAssignedList(List<Leads> unAssignedList) {
        this.unAssignedList = unAssignedList;
    }

    public void setListInventory(List<Inventory> listInventory) {
        this.listInventory = listInventory;
    }
}

2 个答案:

答案 0 :(得分:0)

对不起,如果我输入错了,但是这里的代码没有问题。 问题可能出在应用程序的其他部分。 您设置的数据可能是扩展当前数据的数据。

例如您的

GlobalServices instance = GlobalServices.getInstance()
List<Inventory> listInventory1 = new ArrayList<>();
listInventory1.add(new Inventory());
instance.setListInventory(listInventory1); // now your inventory have one item

// In some where else in your project
List<Inventory> listInventory2 = instance.getListInventory(); // lisInventorys.size() equals 1
// Then you add more data to listInventory2 by mistake
listInventory2.add(new Inventory()); // listInventory2.size() equals 2
// Then you set back listInventory2 to your global service
instance.setListInventory(listInventory2); // now your inventory have two item

因此,数据实际上已被覆盖,只是意外扩展了数据。

答案 1 :(得分:0)

问题在于您只是在GlobalServices中为列表分配新引用,而没有创建新列表。这意味着,一旦您从代码中的其他位置修改了此引用,它也将反映在GlobalServices列表中。您所要做的就是:

    public void setAssignedList(List<Leads> assignedList) {
        this.assignedList = new ArrayList<>(assignedList);
    }

    public void setUnAssignedList(List<Leads> unAssignedList) {
        this.unAssignedList = new ArrayList<>(unAssignedList);
    }

    public void setListInventory(List<Inventory> listInventory) {
        this.listInventory = new ArrayList<>(listInventory);
    }

这样,将在内存中为每个列表创建一个新副本,并且数据将被覆盖。