Java: Initialize ArrayList in field OR constructor?

后端 未结 1 704
甜味超标
甜味超标 2021-01-02 11:19

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 init

1条回答
  •  旧巷少年郎
    2021-01-02 11:39

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

    You can even be explicit and use this:

    public GroceryBill(Employee Clerk) {
        this.itemsInGroceryList = new ArrayList();
    }
    

    0 讨论(0)
提交回复
热议问题