如果 ArrayList 未初始化为字段,则在将项目添加到 ArrayList 时出现 NullPointerException。谁能解释为什么?
当我将 ArrayList 初始化为字段时工作:
public class GroceryBill {
private String clerkName;
private ArrayList<Item> itemsInGroceryList = new ArrayList<Item>();
private double total;
//Constructs a grocery bill object for the given clerk
public GroceryBill(Employee Clerk) {
this.clerkName = Clerk.getEmployeeName();
this.total = 0.0;
}
public void add(Item i) {
itemsInGroceryList.add(i);
}
}
当我将 ArrayList 声明为字段然后在 Class 构造函数中初始化它时不起作用:
public class GroceryBill {
private String clerkName;
private ArrayList<Item> itemsInGroceryList;
private double total;
//Constructs a grocery bill object for the given clerk
public GroceryBill(Employee Clerk) {
this.clerkName = Clerk.getEmployeeName();
this.total = 0.0;
ArrayList<Item> itemsInGroceryList = new ArrayList<Item>();
}
public void add(Item i) {
itemsInGroceryList.add(i);
}
}