在字段或构造函数中初始化

在字段或构造函数中初始化

本文介绍了Java:在字段或构造函数中初始化 ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 ArrayList 未初始化为字段,则在将项目添加到 ArrayList 时,我收到 NullPointerException.谁能解释一下为什么?

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?

当我将 ArrayList 初始化为字段时有效:

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

}

当我将 ArrayList 声明为一个字段然后在类构造函数中初始化它时不起作用:

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

}

推荐答案

因为构造函数中的版本正在创建一个刚好与您的成员字段命名相同的新变量,而该成员字段仍未设置.这称为变量遮蔽,其中新创建的变量遮蔽/隐藏成员字段.

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

你甚至可以明确地使用this:

You can even be explicit and use this:

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

这篇关于Java:在字段或构造函数中初始化 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:11