Java: Initialize ArrayList in field constructor OR?

I get a NullPointerException when adding an element to an ArrayList if the ArrayList is not initialized as a field. Can someone explain why?

WORKS when I initialize an 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 an 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); } } 
+7
source share
1 answer

Since the version in the constructor creates a new variable that is simply called the same as your member field, and the member field remains unset. This is called variable shading, where a newly created variable hides / hides the member field.

You need to get rid of the type declaration in the constructor so that you refer to the member variable:

 public GroceryBill(Employee Clerk) { itemsInGroceryList = new ArrayList<Item>(); } 

You can even be explicit and use this :

 public GroceryBill(Employee Clerk) { this.itemsInGroceryList = new ArrayList<Item>(); } 
+11
source

All Articles