gpt4 book ai didi

java - 将对象添加到列表

转载 作者:行者123 更新时间:2023-12-01 17:49:21 24 4
gpt4 key购买 nike

这可能是一个非常简单的解决方案,但我刚刚开始学习 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com