我有Warehouse
类型的数组列表。每个仓库都有库存量。方法getStock()
返回库存水平。
我有ArrayList
Warehouse
。我想获取列表中每个仓库的库存并将其添加到列表中。
我的代码:
import java.util.*;
public class Warehouses {
ArrayList<Warehouse> warehouses = new ArrayList<Warehouse>();
public Warehouses() {
warehouses.add(new Warehouse("W1", 20, "RM13 8BB"));
warehouses.add(new Warehouse("W2", 28, "RM13 8BB"));
warehouses.add(new Warehouse("W3", 17, "RM13 8BB"));
}
public void stockList() {
ArrayList<Integer> stockList = new ArrayList<Integer>();
for(Warehouse warehouse : warehouses) {
Integer stock = warehouse.getStock();
System.out.println(stock);
}
}
}
class Warehouse
{
// instance variables - replace the example below with your own
private String warehouseID;
private int warehouseStock;
private String location;
/**
* Constructor for objects of class Warehouse
*/
public Warehouse(String warehouseID, int warehouseStock, String location)
{
// initialise instance variables
warehouseID = warehouseID;
warehouseStock = warehouseStock;
location = location;
}
public int getStock(){
return warehouseStock;
}
public String getLocation() {
return location;
}
}
当我致电stockList()
时,我只得到三个空值。这有什么不对?
由于
答案 0 :(得分:3)
将Warehouse
的构造函数参数分配给类成员变量,而不是自己重新分配局部变量
public Warehouse(String warehouseID, int warehouseStock, String location) {
this.warehouseID = warehouseID;
this.warehouseStock = warehouseStock;
this.location = location;
}