java - 在ArrayList中添加默认值

标签 java arrays eclipse arraylist

我有一个具有以下格式的产品:

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

但是,这显示了 JMS343RQ090 无法解析为变量的错误。我以为我此时正在创建它们,因为它只是一个字符串。任何帮助都会很棒。谢谢!

工作解决方案如下图:

        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/

相关文章:

java - 组织导入 Eclipse 方法

eclipse - HTTP 状态 404 描述 请求的资源 () 不可用。 Apache Tomcat/7.0.27

java - 找不到屏幕录制的视频 (/sdcard/capture.mp4") - Mediaprojection API

java - 在 Maven 中部署用于生产的 jar

java - GridBagLayout:设置组件的位置

c - 循环遍历字符串数组,然后使用 scanf_s c 转换为字节

java - Android - 在我的 onStop() 方法中写入文件使我的应用程序崩溃

javascript - 使用npm csv-writer写入csv文件不起作用,但没有出现错误消息

c - 重新分配内存以增加 C 中数组的大小

android - 如何在 Eclipse 调试器中查看崩溃原因