I'm guessing that I'm just going about this all wrong, but I was curious so I thought I'd ask.
I'm working on a reservation system just to brush up on some design patterns. I have a Room class and Customer class, and I want to keep a schedule of which Customers are in which Rooms on which dates.
My initial idea was based on the fact that a date range and room should always determine the customer: (DateRange, Room) -> Customer
This would be easy to accomplish using a database, but I was hoping to stick with some sort of native data structure if at all possible, so I started by using a hashmap indexed with a Reservation object as a key and a Customer object as a value:
HashMap<Reservation, Customer> schedule; The Reservation object would contain a start date, end date, and room object.
// Something kind of like this:
public Reservation(Date startDate, Date endDate, RoomComponent room)
this.startDate = startDate;
this.endDate = endDate;
this.room = room;
I overrode (is that a word?) the equals method of the Reservation class to return true if the dates overlapped. If hashmaps used the equals method as the primary comparator, this would work perfectly, but instead they use the hashcode method first to increase efficiency.
// The overridden equals method:
public boolean equals(Reservation r)
// Reservations are equal if the rooms are the same and the dates overlap.
&& ((r.getStartDate() >= this.startDate && r.getStartDate() <= this.endDate)
|| (r.getEndDate() >= this.startDate && r.getEndDate() <= this.endDate))
So my options seemed to be to either override the hashcode method in the reservation (which I know I should be doing anyway), or override the containsKey method in the Schedule class. The problem is that I can't think of a way to make overlapping dates have the same hashcode, which leads me to believe that it's just a bad idea to use the equals method to do this kind of comparison. It's also a bad idea to override the containsKey method because it completely defeats the purpose and efficiency of a hashmap.
So... is there another data structure that would work better for this, or am I just completely off on all of this, and should restructure everything?