1

My goal is to have a list of cars as an Object so that, I can retrieve a Car from that list. As well as get details of the cars. Can someone point me to the right direction

What I have done so far.

  1. Create a class called Car and have the variables CarNum, carName, carPlate;
  2. generated getters and setters for the variables and a toString as the carName
  3. Create a class called CarCollection as follows

.

 public class CarCollection {
        private List<CarItem> mCarList;



        public void addVan(CarItem v) {
            mCarList.add(v);
        }

        public List<CarItem> getCarList() {
            return mCarList;
        }

The following test doesn't work. Why?

public class TestCarCollectionprocess {

    public static void main(String[] args) {

        CarItem car1 = new CarItem();
        car1.setmCarName("Pedro");
        car1.setmCarNum(1);

        CarItem car2 = new CarItem();
        car2.setmCarName("Rene");
        car2.setmCarNum(2);

        CarCollection carList = new CarCollection();        
        carList.addCar(car1);
        carList.addCar(car2);
        System.out.println(carList.getCarList());
    } 
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255

2 Answers2

3

What I see from your code, you should get NullPointerException in addVan method since you didn't initialize List, so change it like this:

 private List<CarItem> mCarList = new ArrayList<>();
Adnan Isajbegovic
  • 2,227
  • 17
  • 27
0

You are trying to add a CarItem to the CarCollection's mCarList without ever instantiating the list so you should be getting a null reference exception. In your carCollection class, create a constructor that sets

mCarList = new List<CarItem>();
Trevor Ward
  • 602
  • 3
  • 12