简体   繁体   中英

Check if array is NULL at a Specific Index returns NullPointerException

I am trying to add an object of type Car to an Array of cars, I do not have a specific index within the array that I want the car to go into , I just want to add the car to the first empty and available index that doesn't have a car object already in there. Here is my code:

protected static final int MaxCars = 5;
protected Car[] cars = new Car[MaxCars];

public void addCar(Car c)
{
    for(int i = 0; i < MaxCars; i++)
    {
        if (cars[i] == null)
        {
            cars[i] = c;
            break;
        }
    }
    incrementNumInTeam();
}

On the if statement inside the for loop I am getting the a NullPointerException .. how can I overcome this?

Your variable cars is likely null at the time the if block is called. Your error is present but likely elsewhere in your code. Check to be sure that you're not shadowing the cars variable and that the variable being initialized is the same one being read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM