I have a public class called Tournament which has a nested private static class called 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]);
}
}
}
So when I create an object of Tournament. The constructor calls the generateTeams() method.When I run this , it is returning a NullPointerException at the line: this.teams[i] = new Team(); (Which is highlighted in bold).
For some reason it is not instantiating the Team() object and hence assigning a null value to teams[i]
New to OOPS and nested classes. If possible explain in detail.
Thanks in advance.
You need to instantiate the array first
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]);
}
But as you are adding Team
Objects to a queue, why do you even need an Array?