Cardona Jeison
Cardona Jeison

Reputation: 77

Java, Exception in thread "main" java.lang.NullPointerException caused due to not initializing an object

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

Answers (3)

aliteralmind
aliteralmind

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

Elliott Frisch
Elliott Frisch

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

tkt986
tkt986

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

Related Questions