这可能是一个非常简单的解决方案,但我刚刚开始学习 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;
}
}
最佳答案
您只需将新创建的 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);
}
}
关于java - 将对象添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52223787/