I'me getting a NullPointerException when adding an item to an ArrayList IF the ArrayList is isn't initialized as a field. Can anyone explain why?
WORKS when I initialize the ArrayList as a field:
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);
}
}
DOES NOT WORK when I declare the ArrayList as a field then initialize it in the Class constructor:
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);
}
}
final, since you never overwrite it.