-4

I keep on getting a null pointer exception when i invoke the add method the code seems fine but i dont know what is wrong.

public class CarRunner {

public static void main(String[] args) {
    TrafficLight light = new TrafficLight();
    RoadRunnable run1 = new RoadRunnable(1,light);
    String car="car";
    for (int i =0;i<100;i++)
    {
        car="car"+i;
        run1.add(car);
    }

    Thread traffic1 = new Thread(run1);
    traffic1.start();
}

}

public class RoadRunnable implements Runnable{

private LinkedList<String> queue;

private int number;

private TrafficLight light;

public RoadRunnable(int roadNumber, TrafficLight aLight) 

{ 
    number = roadNumber;

    light = aLight;

}

public void add(String car)

{

    queue.add(car);


}
 }
Android Developer
  • 987
  • 1
  • 8
  • 22

4 Answers4

2

Your queue is not intantiated. In your constructor, you might want to do:

queue = new LinkedList<String>();
vee
  • 38,255
  • 7
  • 74
  • 78
0

Null pointer exception happens when you try to access a null object method or params. In your code you have not initialized the queue:

private LinkedList<String> queue

and hence facing Null pointer exception while trying to add the elements in the queue using queue.add(car); in add method of your RoadRunnable class.

You should initialized your queue either at the declaration or in the constructor, something like:

public RoadRunnable(int roadNumber, TrafficLight aLight) 
{ 
    // queue initilization
    queue = new LinkedList<String>();
    number = roadNumber;
    light = aLight;
}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

Nothing in the RoadRunnable class ever creates the actual LinkedList for the queue variable to point to; therefore queue is null and you get the NPE when you try to use it.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
0

You are not initialize the queue.

private LinkedList<String> queue = new LinkedList<String>();

instead of

private LinkedList<String> queue;

Reference for initializing LinkedList

newuser
  • 8,338
  • 2
  • 25
  • 33