Reputation: 77
Help me with this, "Exception in thread "main" java.lang.NullPointerException" thanks
private List< PosibleTerreno> posibles_terrenos;
private List< PosibleTerreno> terrenos_validos;
//-------------------------------
int cantidad = this.posibles_terrenos.size();
for (int i = 0 ; i < cantidad ; i++)
{
if(this.posibles_terrenos.get(i).get_validez() == true)
{
this.terrenos_validos.add(this.posibles_terrenos.get(i));
}
}
Upvotes: 1
Views: 119
Reputation: 20163
You have declared these variables
private List< PosibleTerreno> posibles_terrenos;
private List< PosibleTerreno> terrenos_validos;
but you have not initialized them. You need to do something along the lines of
private List< PosibleTerreno> posibles_terrenos = new ArrayList<PosibleTerreno>();
private List< PosibleTerreno> terrenos_validos = new ArrayList<PosibleTerreno>();
Otherwise, both lists are null
, and attempting to reference any of their functions...doesn't even make sense, because there's no "their" there. They're nothing. So attempting this
int cantidad = this.posibles_terrenos.size();
will obviously result in a NullPointerException
.
(+1 for three homophones in a row.)
Upvotes: 5
Reputation: 201477
You need to initialize your List(s)
, you might use a ArrayList and/or a LinkedList perhaps with -
private List<PosibleTerreno> posibles_terrenos = new ArrayList<PosibleTerreno>();
private List<PosibleTerreno> terrenos_validos = new LinkedList<PosibleTerreno>();
With Java 7 and above, you can also use the diamond operator like so -
private List<PosibleTerreno> posibles_terrenos = new ArrayList<>();
private List<PosibleTerreno> terrenos_validos = new LinkedList<>();
Upvotes: 3
Reputation: 1028
do this before executing the line throwing the exception.
private List< PosibleTerreno> posibles_terrenos = new ArrayList<PosibleTerreno>();
private List< PosibleTerreno> terrenos_validos = new ArrayList<PosibleTerreno>();
Upvotes: 2