Static Inner class 实例化时返回null
Static Inner class returning null when instantiating
我有一个名为 Tournament 的 public class,它有一个名为 Team 的嵌套私有静态 class。
public class Tournament {
private Team[] teams;
private static int noOfTeams;
private Queue<Team> queue = new LinkedList<>();
Team teamA,teamB,winner;
public Tournament(int noOfTeams)
{
this.noOfTeams = noOfTeams;
generateTeams();
}
private void generateTeams()
{
for (int i = 0; i < noOfTeams; i++)
{
this.teams[i] = new Team(); // Returning Null here
this.teams[i].setId(i);
this.teams[i].setRank(i);
queue.add(this.teams[i]);
}
}
}
所以当我创建一个 Tournament 对象时。构造函数调用 generateTeams() method.When I 运行 this ,它在以下行返回 NullPointerException:
this.teams[i] = 新团队(); (以粗体突出显示)。
出于某种原因,它没有实例化 Team() 对象,因此将空值分配给 teams[i]
OOPS 新手和嵌套 classes。可以的话详细解释一下。
提前致谢。
需要先实例化数组
this.teams = new Team[noOfTeams];
for (int i = 0; i < noOfTeams; i++)
{
this.teams[i] = new Team();
this.teams[i].setId(i);
this.teams[i].setRank(i);
queue.add(this.teams[i]);
}
但是 当您将 Team
个对象添加到队列时,为什么您甚至需要一个数组?
我有一个名为 Tournament 的 public class,它有一个名为 Team 的嵌套私有静态 class。
public class Tournament {
private Team[] teams;
private static int noOfTeams;
private Queue<Team> queue = new LinkedList<>();
Team teamA,teamB,winner;
public Tournament(int noOfTeams)
{
this.noOfTeams = noOfTeams;
generateTeams();
}
private void generateTeams()
{
for (int i = 0; i < noOfTeams; i++)
{
this.teams[i] = new Team(); // Returning Null here
this.teams[i].setId(i);
this.teams[i].setRank(i);
queue.add(this.teams[i]);
}
}
}
所以当我创建一个 Tournament 对象时。构造函数调用 generateTeams() method.When I 运行 this ,它在以下行返回 NullPointerException: this.teams[i] = 新团队(); (以粗体突出显示)。
出于某种原因,它没有实例化 Team() 对象,因此将空值分配给 teams[i]
OOPS 新手和嵌套 classes。可以的话详细解释一下。
提前致谢。
需要先实例化数组
this.teams = new Team[noOfTeams];
for (int i = 0; i < noOfTeams; i++)
{
this.teams[i] = new Team();
this.teams[i].setId(i);
this.teams[i].setRank(i);
queue.add(this.teams[i]);
}
但是 当您将 Team
个对象添加到队列时,为什么您甚至需要一个数组?