我有一个称为Tournament的公共类,它有一个嵌套的私有静态类,称为Team。
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]);
}
}
}
所以当我创建一个锦标赛对象时。构造函数调用generateTeams()方法。当我运行this时,它在以下行返回NullPointerException: this.teams [i] = new Team(); (以粗体突出显示)。
由于某种原因,它没有实例化Team()对象,因此没有为team [i]分配空值
OOPS和嵌套类的新手。如果可能的话,请详细解释。
谢谢。
答案 0 :(得分:2)
您需要先实例化数组
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
对象添加到队列中时,为什么甚至需要一个数组?