Reputation: 11
When I manage to recall the contructor from the Teams class (which store the List<Players>
in it) is obvs null
. Where do I populate that List? Do I need to populate it inside the Players class? Or inside the Team class?
I am working with Spring recently.
I'll leave the examples of the 3 class. Squadre means Teams, Giocatori means Players. (using lombok)
public class Squadra {
private String nomeSquadra;
private List<Giocatori> rosaAttuale;
private int goalFatti;
private int goalSubiti;
private int differenzaReti;
private int posizioneInCampionato;
private double valoreRosa;
public void addGiocatori(Giocatori g) {
rosaAttuale.add(g);
}
public void removeGiocatori(Giocatori g) {
rosaAttuale.remove(g);
}
}
public class Giocatori {
String nomeGiocatore;
String cognomeGiocatore;
int eta;
int numeroMaglia;
public Giocatori() {
}
}
@Component
public class SquadreRepo {
@Getter
private List<Squadra> dataBaseSquadre = new ArrayList<Squadra>();
public SquadreRepo() {
dataBaseSquadre.add(new Squadra(null, null, 0, 0, 0, 0, 0))
}
public void addSquadra(Squadra s) {
dataBaseSquadre.add(s);
}
public void removeSquadra(Squadra s) {
dataBaseSquadre.remove(s);
}
}
Upvotes: 0
Views: 191
Reputation: 26
Your list of players rosaAttuale of class Squadra is never initialized in the code above. You initialize your team in SquadreRepo by calling the constructor with
dataBaseSquadre.add(new Squadra(null, null, 0, 0, 0, 0, 0))
The second parameter is presumably the rosaAttuale list (assuming the constructor was generated using Lombok), so your list is null and you can never add any players. Instead, try to initialize it with an empty list, e.g.:
dataBaseSquadre.add(new Squadra(null, new ArrayList<>(), 0, 0, 0, 0, 0));
Also see these questions for properly initializing collections when using Lombok builders:
Upvotes: 1
Reputation: 12665
Your problem is not very clear but I understand that you get a NullPointerException
when you run this method:
public void addGiocatori(Giocatori g) {
rosaAttuale.add(g); //<- rosaAttuale is null
}
If that's what you mean, indeed, you need to initialize the list when you build the class Squadra
.
To do that, there are at least two options:
Either in the constructor:
public Squadra() {
this.rosaAttuale = new ArrayList<>();
}
Or in the field declaration directly:
private final List<Giocatori> rosaAttuale = new ArrayList<>();
Upvotes: 0