1

I have a custom class "CarSharing", with an attribute "availableCars". An ArrayList availableCars is inizialized in the constuctor . When I create a CarSharing object and try to call the ArrayList in a method I get a java.lang.NullPointerException.

public class CarSharing {    

  private ArrayList<Car> availableCars;

  public CarSharing() {
    ArrayList<Car> availableCars = new ArrayList<Car>();  
    // I can use the List inside of the constructor 
  }    

  public void addAvailableCar(Car newCar) {
     availableCars.add(newCar); 
// Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at CarSharing.addVerfuegbaresAuto(CarSharing.java:12)
  }

Any Ideas? Thank you.

TamTiTam
  • 13
  • 1
  • 1
  • 5

3 Answers3

6

You don't initialize the availableCars you are making a local variable in the constructor. To fix it simple remove the ArrayList in the constructor.

private ArrayList<Auto> availableCars;

public CarSharing() {
  availableCars = new ArrayList<Car>();
} 
Walshy
  • 850
  • 2
  • 11
  • 32
2

The code should be something like this

public class CarSharing {    

    private ArrayList<Auto> availableCars;

    public CarSharing() {
        // use the class attribute directly in the constructor
        // This way, each new object will have its own list of available cars
        availableCars = new ArrayList<Car>();
    }

    public void addAvailableCar(Car newCar) {
        availableCars.add(newCar); 
    }
}

Now when you will make an object the class like below

CarSharing car = new CarSharing(); // This object will have a new arraylist initialized in it
car.addAvailableCar(...); // will work without any problem now
Saif Asif
  • 5,516
  • 3
  • 31
  • 48
0

The problem is you are trying to use a variable before its given a place in memory.You have declared available cars that is fine but you have declared it in constructor again that is wrong.

The object you declared in the class has no relation with the one in constructor. Thus when you call availableCars.add(newCar); It gives null pointer exception as you haven't defined available cars yet. You have just declared it.

Forget about availableCars in constructor as it has became local object in contructor itself.

For your concept.

Declaration: You are declaring that something exists, such as a class, function or variable. You don't say anything about what that class or function looks like, you just say that it exists.

Definition: You define how something is implemented, such as a class, function or variable, i.e. you say what it actually is.