我有一个具有以下格式的产品:
public Item(String barcode, double price, int inStock) {
if (barcode == null) {
barcode = "";
}
if (price < 0) {
price = 0;
}
if (inStock < 0) {
inStock = 0;
}
this.barcode = barcode;
this.price = price;
this.inStock = inStock;
}
还有一个 ArrayList
将项目存储在另一个类中:
public class Inventory {
private ArrayList<Item> currentInventory;
public Inventory() {
this.currentInventory = new ArrayList<Inventory>();
}
/**
* Adds default products to the inventory
*/
public void inventoryDefault() {
this.currentInventory("JMS343", 100.00, 5);
this.currentInventory("RQ090", 50.00, 20);
}
我不知道如何添加 2 个项目作为默认值,或者始终添加到 currentInventory
中,直到被用户删除。我也尝试过:
public void inventoryDefault() {
this.currentInventory.add(JMS343, 100.00, 5);
this.currentInventory.add(RQ090, 50.00, 20);
}
但是,这显示了 JMS343
和 RQ090
无法解析为变量的错误。我以为我此时正在创建它们,因为它只是一个字符串。任何帮助都会很棒。谢谢!
工作解决方案如下图:
public void inventoryDefault() {
this.currentInventory.add(new Item("JMS343", 100.00, 5));
this.currentInventory.add(new Item("RQ090", 50.00, 20));
}
最佳答案
对 Inventory
类的构造函数执行此操作
public Inventory() {
this.currentInventory = new ArrayList<Inventory>();
this.currentInventory.add(new Item("JMS343", 100.00, 5));
this.currentInventory.add(new Item("RQ090", 50.00, 20);
}
关于java - 在ArrayList中添加默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34109333/