将对象添加到列表

时间:2018-09-07 13:39:50

标签: java list

这可能是一个非常简单的解决方案,但我刚刚开始学习Java。我想将每个实例化的产品添加到productList中。有什么方法可以解决此问题而无需修改访问修饰符?

public class Product {
    private int id;
    private String name;
    private float defaultPrice;
    private Currency defaultCurrency;
    private Supplier supplier;
    private static List<Product> productList;
    private ProductCategory productCategory;

    public Product(float defaultPrice, Currency defaultCurrency, String name) {
        this.id = IdGenerator.createID();
        this.defaultPrice = defaultPrice;
        this.defaultCurrency = defaultCurrency;
        this.name = name;
    }
}

4 个答案:

答案 0 :(得分:2)

您可以将新创建​​的Product添加到其构造函数中的列表中:

public class Product {

    private int id;
    private String name;
    private float defaultPrice;
    private Currency defaultCurrency;
    private Supplier supplier;
    private static List<Product> productList = new LinkedList<>();
    private ProductCategory productCategory;

    public Product(float defaultPrice, Currency defaultCurrency, String name){
        this.id = IdGenerator.createID();
        this.defaultPrice = defaultPrice;
        this.defaultCurrency = defaultCurrency;
        this.name = name;
        productList.add(this);
    }
}

答案 1 :(得分:1)

更改初始化行

private static List<Product> productList;

private static List<Product> productList = new LinkedList<>();

添加productList.add(this)作为构造函数的最后一行。

因此,每次调用Product构造函数时,它将将此实例添加到静态列表中。

答案 2 :(得分:1)

Peter LawreyMureinik's answer的注释部分中提到的那样,在POJO中拥有static集合不是最佳解决方案。

我建议使用简单的外观。这将列表的存在限制为门面寿命,并且在POJO中不包含集合的逻辑。

public class FacadeProduct {

    private List<Product> cacheProduct = new ArrayList<>();

    public Product createProduct(float defaultPrice, Currency defaultCurrency, String name){
        Product p = new Product(defaultPrice, defaultCurrency, name);
        cacheProduct.add(p);
        return p;
    }
}

这将非常容易使用。

public static void main(String ars[]){
    {
        FacadeProduct f = new FacadeProduct();
        {
            Product p1 = f.createProduct(1f, null, "test1");
            Product p2 = f.createProduct(1f, null, "test2");
            Product p3 = f.createProduct(1f, null, "test3");
            // Here, the list have 3 instances in it
        }
        // We lose the p1, p2, p3 reference, but the list is still holding them with f.
    }
    //Here, we lose the f reference, the instances are all susceptible to be collected by the GC. Cleaning the memory
}

答案 3 :(得分:0)

使用null初始化productList,然后按如下所示修改构造函数:

public Product(float defaultPrice, Currency defaultCurrency, String name) {
        this.id = IdGenerator.createID();
        this.defaultPrice = defaultPrice;
        this.defaultCurrency = defaultCurrency;
        this.name = name;
        if (productList == null) productList = new ArrayList<>();
        productList.add(this);
    }