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());
    } 
}
4
  • 1
    What doesn't work exactly? Commented Apr 28, 2016 at 18:51
  • please provide what you got in output. Commented Apr 28, 2016 at 18:52
  • I don't see an addCar method in your CarCollection class and I don't see if you are fully constructing the private List<CarItem> mCarList; Commented Apr 28, 2016 at 18:53
  • 1
    Your should READ the exception you get. It tells exactly what and where the problem is. stackoverflow.com/questions/218384/… Commented Apr 28, 2016 at 19:04

2 Answers 2

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<>();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This was the answer I was looking for!
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>();

1 Comment

no, IList is an interface, List is an implementation of the interface

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.