I have created a class called Month that extends Calendar, which I am using to hold events for a given month. I have several years worth of Month objects stored in a TreeSet. Most of the events I want to record last for several months and are specified only by their start month (and a duration, in months). I want to be able to do this:
for ( Event e : events )
{
for ( Month aMonth : myMonths )
{
// check if this is a start month for e
// if it is, call aMonth.addEvent(e);
// and also add e to the next e.getDuration() months of myMonths
// and then start checking again from the month where we called addEvent(e)
// in case there is another occurrence of e starting
// before the first one has finished
}
}
It's the part in capitals I'm having trouble with. I tried using an iterator instead of a foreach loop, and having a separate loop when a start date was found which used the iterator to add e to the next x months, but I couldn't then get the iterator back to where it started. It looks like ListIterator has a previous() method, but I wanted to use a SortedSet rather than a List, to ensure duplicates are avoided (although perhaps this inclination is wrong?)
It feels like it would be much easier to do this with a plain old array, but the collection is useful for other parts of the program. Perhaps I can use multiple iterators and just "use them up" as needed for these forays into months just beyond my main "bookmark" iterator? Doesn't exactly seem elegant though. Or is there a hack for "peeking" beyond where my iterator is actually pointing?
I am quite new to all this, so I may just be making a design error. All advice welcomed!
What's do the Event and Month objects look like? I think what you had will work:
for(Event event : events) {
for(Month aMonth : myMonths) {
if(aMonth >= event.startMonth && aMonth <= event.startMonth+event.duration) {
aMonth.add(event);
}
}
}
Alternatively you could flip it around and go the other way, make your outer iterator the Months and your inner iterator the Events. That should work too, the if() condition would probably be the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With