Vladislav Bogdanov
Vladislav Bogdanov

Reputation: 1891

Strange exception

Hey guys we are trying to make a client-server racing game for our semester project but we have some strange error

public void updatePosition(int id, ArrayList<Point2D.Float> positions){
    if(id==1){
        for (int i = 1; i < game.getS().getVehicles().size(); i++)
        {
            game.getS().getVehicles().get(i).updatePosition(positions.get(i));              
        }

    }else if(id==2){
        game.getS().getVehicles().get(1).updatePosition(positions.get(0));              
        for (int i = 2; i < game.getS().getVehicles().size(); i++)
        {
            game.getS().getVehicles().get(i).updatePosition(positions.get(i));  
        }

this is our code

and the exception is in this exact row: game.getS().getVehicles().get(1).updatePosition(positions.get(0));

Upvotes: 1

Views: 128

Answers (2)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

A NullPointerException can occur in many places in this small fragment of code.

Basically, when you have an expression of the kind a.b().c(), a NullPointerException can be thrown if a is null, or if b() returns null.

If you are uncertain that all of the parts of such an expression are not null, you have to perform explicit checking:

if (a != null) {
  WhateverObject intermediate = a.b();

  if (intermediate != null) {
    intermediate.c(); 
  }
}

Upvotes: 1

duffymo
duffymo

Reputation: 308733

References are initialized to null by default. If you create a collection or array, and fail to initialize references, they'll be null by default.

Upvotes: 4

Related Questions