Search code examples
javaarraylistinventory

How to use previously defined class in arraylist


I am writing an addition to a java inventory problem that uses an arraylist to write methods to add, search for, etc. items in an inventory.

I am using another class called InventoryItem which has variables for sku, itemName, price, and stock.

I would like to know if I am on the right track in using a perviously defined class in writing a method to add an item.

import java.util.*;

public class Warehouse {

      private ArrayList<InventoryItem> inventory = new ArrayList<InventoryItem>();

      public static void addItem(InventoryItem i ) 

          inventory.add(i);

      }

      public static void main(String [] args) {

           addItem();    

      }
}

This is the InventoryItem class;

public class InventoryItem {

   private int sku;
   private String itemName;
   private double price;
   private int stock;



   public InventoryItem (int sku, String itemName, double price, int stock) {

   this.sku = sku;      
   this.itemName = itemName;
   this.price = price; 
   this.stock = stock;

}

   public int getSku() {

      return sku;

   }


   public String getitemName () {

      return itemName;

   }

   public void setPrice (double price) {

      this.price = price;

   }   

   public double getPrice () {

      return price;

   }

   public void setStock(int stock) {

      this.stock = stock;

   }


   public int getStock() {

      return stock;

   }
    @Override
   public String toString() {

      return String.format("[%d ,%s ,%1.2f ,%d]", sku, itemName, price, stock);

   }

   public static void main(String[] args) {
      InventoryItem itemName = new InventoryItem(1, "asdf", 2.4, 5);
      System.out.println(itemName);

   }

}

Solution

  • The major problem with your addItem() method is that it is static, so it won't be able to access the warehouse list, which is an instance variable that can only be accessed from an instance.

    To fix this (and other) problems, try this:

    public class Warehouse {
        private List<InventoryItem> inventory = new ArrayList<InventoryItem>();
    
        public void addItem(InventoryItem i) 
            inventory.add(i);
        }
    
        public static void main(String [] args) {
            // create a Warehouse instance
            Warehouse warehouse = new Warehouse();
            // create an InventoryItem instance 
            InventoryItem i = new InventoryItem(sku, itemName, price, stock);
            // add the InventoryItem to the Warehouse
            warehouse.addItem(i);    
        }
    }