我试图弄清楚为什么 this.team = new ArrayList() 必须在构造函数中?
它没有,它必须在使用之前进行初始化。只要您之前不调用 printPlayer() 或 addPlayer(),您就可以在任何您想要的地方初始化它。
为什么我不能在方法中初始化 this.team = new ArrayList()?
你实际上可以。看这个例子:
public void addPlayer(Player player) {
if (team == null) {
team = new ArrayList();
}
team.add(player);
}
public void printPlayers() {
if (team != null) {
for (Player p : team) {
System.out.println(p);
}
}
}
但是当它在方法中初始化时,它只列出最后一个给定的添加到列表中。在方法中初始化它是错误的吗?
不,这没有错。如果您按照上面示例的方式进行操作,它通常被称为“延迟初始化”或“按需”。
另外,将其初始化为 private ArrayList team = new ArrayList(); 有什么区别?在构造函数之前?
不多,区别在于初始化的时间。
public class Example {
public static List<T> myList = new ArrayList<T>(); // this is done first
public static List<T> aList;
public List<T> someList;
static {
// this is also done first (on class load)
aList = new ArrayList<T>();
}
{
// this is done right before the constructor (I believe)
// it is called an 'initialization block'
someList = new ArrayList<T>();
}
public Example() {
// this one you already know...
}
}