Java的:在野外或构造函数初始化ArrayList的? [英] Java: Initialize ArrayList in field OR constructor?

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

问题描述

I'me增加一个项目时,一个ArrayList中频ArrayList是不是作为一个字段初始化得到一个NullPointerException异常。任何人都可以解释为什么?

工作当我初始化的ArrayList作为一个字段:

 公共类GroceryBill {私人字符串clerkName;
私人的ArrayList<项目> itemsInGroceryList =新的ArrayList<项目>();私人双人总;//构造一个杂货店法案对象为给定的店员
公共GroceryBill(员工员){    this.clerkName = Clerk.getEmployeeName();
    this.total = 0.0;}公共无效添加(项目一){    itemsInGroceryList.add(ⅰ);
}}

当我宣布ArrayList的一个领域,然后在类的构造函数初始化它不工作:

 公共类GroceryBill {私人字符串clerkName;
私人的ArrayList<项目> itemsInGroceryList;私人双人总;//构造一个杂货店法案对象为给定的店员
公共GroceryBill(员工员){    this.clerkName = Clerk.getEmployeeName();
    this.total = 0.0;
    ArrayList的<项目> itemsInGroceryList =新的ArrayList<项目>();}公共无效添加(项目一){    itemsInGroceryList.add(ⅰ);
}}


解决方案

由于在构造函数的版本创建一个新的变量,恰好被命名为与您的成员字段,成员场保持不设置。这被称为可变阴影,在这里新创建的变量被遮蔽/隐藏部件字段

您需要让你引用成员变量在构造函数中摆脱类型声明:

 公共GroceryBill(员工员){
    itemsInGroceryList =新的ArrayList<项目>();
}

您甚至可以明确的,并使用这个

 公共GroceryBill(员工员){
    this.itemsInGroceryList =新的ArrayList<项目>();
}

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

}

解决方案

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆