如何给每个商店对象它自己的库存列表?

找到这个很难,基本上我有三个类:Store类,Stock类,然后是GUI的类。 创建商店时,我希望它拥有它自己的arraryList,以便我可以添加多个库存对象。 (通过GUI完成)。

我试图只包含所需的基本代码,(删除了getter方法,setter方法,默认构造函数compareTo等)

这是类的一些代码(很可能是错误的)

public class Store { private int id; private String name; private String location; private ArrayList  stockItems = new ArrayList (); public Store(int idIn, String nameIn, String locationIn) { id = idIn; name = nameIn; location = locationIn; ArrayList  stockItems = new ArrayList (); } //to add stock items to a store? public void addStockItem(Stock s) { stockItems.add(s); } 

}

股票类

 public class Stock { private int id; private String name; private double price; private int units; public Stock(int idIn, String nameIn, double priceIn, int unitsIn) { id = idIn; name = nameIn; price = priceIn; units = unitsIn; } } 

谁能告诉我,我是否走在正确的轨道上? 在GUI中,我将从GUI中将库存项目添加到特定商店中?

谢谢。

Store的构造函数中,你有

 ArrayList  stockItems = ... 

这实际上是创建一个局部变量stockItems ,而不是更改字段。 为了使它工作正常使用

 stockItems = ...