Reputation: 447
I am getting an error when trying to add a new object to an ArrayList that is an attribute of another class. Let me explain.
UML
I do have 2 classes in my model:
To simplify things let's call Equipo -> Team & Jugador -> Player.
For each Team there will be multiple players, so I have created an ArrayList of type Player as an attribute in the Team class.
Equipo
public class Equipo {
private String nombre;
private LocalDate fechaAlta;
private String continente;
private char clasificado;
private ArrayList <Jugador> listaJugadores; //Muestra la relación
public Equipo(String nombre, LocalDate fechaAlta, String continente, char clasificado) {
this.nombre = nombre;
this.fechaAlta = fechaAlta;
this.continente = continente;
this.clasificado = clasificado;
}
.
.
.
}
Jugador
public class Jugador {
private String jugador;
private int dorsal;
public Jugador(String jugador, int dorsal) {
this.jugador = jugador;
this.dorsal = dorsal;
}
.
.
.
}
MAIN
In the main class I have created and initialized the Teams and Players ArrayLists.
public static Ventana v1;
public static ArrayList <Equipo> listaEquipos;
public static ArrayList <Jugador> listaJugadores;
public static void main(String[] args) {
v1 = new Ventana();
v1.getearComboBox();
v1.setVisible(true);
//Inicializar arrays
listaEquipos = new ArrayList <Equipo>();
listaJugadores = new ArrayList <Jugador>();
I am trying to add a Player to the last Team in the Array
public static void inscribirJugador(String nombreJugador, String dorsalString){
//Conversion del dorsal
int dorsal = Integer.parseInt(dorsalString);
listaEquipos.get(listaEquipos.size()-1).getListaJugadores().add(new Jugador("nombreJugador", dorsal));
}
However I am getting this NullPointerException error that I am not being able to solve. https://i.sstatic.net/HqfgW.jpg
LINE 98: listaEquipos.get(listaEquipos.size()-1).getListaJugadores().add(new Jugador("nombreJugador", dorsal));
Upvotes: 1
Views: 1022
Reputation: 59
If you did not put at least a team in the ArrayList, you are calling getListaJugadores
on a null object.
In fact, if the ArrayList listaEquipos
is empty, you will return null on the method invocation listaEquipos.get(listaEquipos.size() -1)
. You got to have at least one team to retrieve the list of players!
Upvotes: 1