2013-05-01 42 views
1

我有一个股票列表作为一个类,然后是一个具有下面显示的构造函数的商店类。商店有一个链接到股票类的数组列表。在构造函数中使用Arraylist

我如何访问某个商店的数组列表?

E.G.如果我选择店铺argos,我想要它所有的库存。每家店都有自己的股票

public Store(int storeId, String name, String location){ 
     this.storeId = storeId; 
    this.name = name; 
    this.location = location; 
     items = new ArrayList<Stock>(); 
    } 
+1

一个私有的局部变量,一个getter? – Keppil 2013-05-01 14:16:38

回答

3

如果每个Store都有它自己的Stock项目列表中,那么这将是一个属性,或私人实例变量,该类股票。然后可以使用getter访问Store的项目,例如。

public class Store { 
    private List<Stock> items; 

    public Store(List<Stock> items){ 
     this.items = items; 
    } 

    public List<Stock> getStock(){ 
     // get stock for this Store object. 
     return this.items; 
    } 
    public void addStock(Stock stock){ 
     this.getStock().add(stock); 
    } 
} 

然后,您可以使用Stock项目的getter访问商店实例的商品。

1

可以以这种方式提供安全访问,但如果您没有为用户提供密钥并返回库存清单,那么封装效果会更好。

public class Store { 
    private List<Stock> stock; 

    public Store(List<Stock> stock) { 
     this.stock = ((stock == null) ? new ArrayList<Stock>() : new ArrayList<Stock>(stock)); 
    } 

    public List<Stock> getStock() { 
     return Collections.unmodifiableList(this.stock); 
    } 
} 
+0

我最喜欢blackpanther的回答。他的“addStock”是正确的想法。 – duffymo 2013-05-01 17:05:31

0

有很多可能性的列表中设置为Store对象,并用getter可以return列表后面。

public Store(int storeId, String name, String location,ArrayList<Stock> list){ 
    this.storeId = storeId; 
    this.name = name; 
    this.location = location; 
    this.items = new ArrayList<Stock>(); //or any possibility to set list 
} 

public ArrayList<Stock> getListOfStock(){ 
    return this.items; 
} 
1

说实话,我会建议使用HashMap。将每个商店作为关键字或商店ID,然后将库存列表作为值。这将让你简单地做:

Map storeMap = new HashMap<String, List<Stock>(); 
items = storeMap.get(key); 
1
public class Store { 
    private List<Stock> items; 

    public Store(int storeId, String name, String location){ 
     this.storeId = storeId; 
     this.name = name; 
     this.location = location; 
     items = new ArrayList<Stock>(); 
    } 

    public List<Stock> getAllStock(){ 
     return this.items; 
    } 
}