我有一个类如下:
package com.aci.golfgames;
import java.util.ArrayList;
public class Course {
private String name;
private int noOfTees;
private ArrayList<Tee> tees;
public Course(){
// Build a course with some tees.
name = "ABC Country Club";
ArrayList<Tee> tees = new ArrayList<Tee>();
tees.add(new Tee("White", 126, 70.4));
tees.add(new Tee("Red", 128, 75.2));
tees.add(new Tee("Blue", 126, 71.4));
noOfTees = 3;
}
public String getCourseName(){
return this.name;
}
public ArrayList<Tee> getTees(){
return tees;
}
public int getNoOfTees(){
return this.noOfTees;
}
}
当我尝试实例化 ArrayList 字段 tees 时,我创建的 ArrayList 似乎与对象 Course 中声明为字段的 ArrayList 不同。 IOW,this.tees 不同于 tees。如果我删除该行:
ArrayList<Tee> tees = new ArrayList<Tee>();
我在 tees.add(...) 处在运行时遇到空指针异常,我假设是因为 ArrayList 尚未实例化。
这是怎么回事?如何实例化 ArrayList?注意:tees ArrayList 中的条目数会因对象而异,因此 ArrayList 而不仅仅是数组。这里的代码只是定义了一个Course用于测试。
谢谢。
最佳答案
public Course(){
ArrayList<Tee> tees = new ArrayList<Tee>();
}
应该是
public Course(){
tees = new ArrayList<Tee>();
}
通过将其定义为 ArrayList<Tee>
再次在构造函数中,您正在缩小 tees
的范围仅在构造函数中使用构造函数,而其他方法使用 tees
定义为实例范围内的字段。
是的,它实际上会创建一个将在构造函数中使用的新列表。
关于java - 在类构造函数中实例化 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19844907/