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

时间:2013-04-30 17:46:47

标签: java arraylist

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

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

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

public class Store  {

private int id;
private String name;
private String location;


private ArrayList <Stock> stockItems = new ArrayList<Stock> ();


public Store(int idIn, String nameIn, String locationIn) {
    id = idIn;
    name = nameIn;
    location = locationIn;
    ArrayList <Stock> stockItems = new ArrayList<Stock> ();
}





//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中将库存项目添加到特定商店中吗?

感谢。

1 个答案:

答案 0 :(得分:3)

Store的构造函数中,您有

ArrayList <Stock> stockItems = ...

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

stockItems = ...
相关问题