9

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);
}

}
1
  • 1
    Do this when declaring the instance variable itself, and what is more you can make it final, since you never overwrite it. Commented Jan 12, 2013 at 2:00

1 Answer 1

14

Because the version in the constructor is creating a new variable that just happens to be named the same as your member field, and the member field remains not set. This is known as variable shadowing, where the newly created variable is shadowing / hiding the member field.

You need to get rid of the type declaration in the constructor so you're referencing 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>();
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 - for identifying that this is shadowing (not "mak[ing] a local copy of the variable" which is nonsensical from a terminological point of view ...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.