Michal Dobrzycki
Michal Dobrzycki

Reputation: 168

Which data structure should I use in Java?

I'm doing Car Rental app in Java.

  1. I have class Car with Strings RegNo, producer, model and boolean isCarRented.
  2. List of cars I'm keeping in:

    Collection<Car> carList = new HashSet<Car>();

Everything works fine.

Now what I need to do is history/statistic module for whole rental company:

My idea is to:

  1. Create class CarHistory with:

    private static List<String> rentalDates = new ArrayList<String>();

  2. Keeping there dates which I'm gonna add every time the car is rented.

  3. Create data structure to remember each car rental history like this:

    static Map<Car, CarHistory> rentalList = new HashMap<Car, CarHistory>();

Is it a good way? I do have troubles with constructor for single CarHistory in this solution. Not really sure what it should return. Should I create it after first rental? And should create empty List rentalDates for each car to create HashMap?

Upvotes: 0

Views: 241

Answers (1)

Simon
Simon

Reputation: 2733

What you are trying to do is to implement a one-to-one relationship, because a Car has only one CarHistory and one CarHistory concerns only one Car. That is why, the correct way of doing it would be to add field CarHistory carHistory to the class of Car.

In the beginning, the list of CarHistory would be empty. With each reservation, you would simply add one record to the list. The car history would be easily accessible, and the model would match the reality in the most accurate way.

Upvotes: 3

Related Questions