首页 > 解决方案 > 将对象添加到列表

问题描述

这可能是一个非常简单的解决方案,但我刚刚开始学习 Java。我想将每个实例化的产品添加到产品列表中。有没有办法在不修改访问修饰符的情况下解决这个问题?

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;
    }
}

标签: javalist

解决方案


您可以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);
    }
}

推荐阅读