How can I access elements in a java collection outside of my iterator without "losing my place"?

I created a Month class that extends Calendar, which I use to store events for a given month. I have Monthly objects for several years stored in a TreeSet. Most of the events that I want to record the last few months, and are indicated only by their initial month (and 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
    }   
}

This is the part in the capitals that I encountered. I tried using an iterator instead of a foreach loop and had a separate loop when a start date was found that used the iterator to add e in the next x months, but I could not then return the iterator to where it was running. It looks like ListIterator has a previous () method, but I wanted to use SortedSet rather than List to avoid duplication (although maybe this deviation is wrong?)

, , . , " ", , ""? . "" , ?

, . !

+3
3

, , . , for , (m * n) . , , , , , .

, . , ( - , , , , for).

Edit

, , , , ( , ). LinkedList ( ), , , , , t :

LinkedList<Month> monthList = new LinkedList<Month>();
var i = monthList.getIterator();
for(Event ev : events)
{
    shiftList(monthList, i, ev);
    for(Month m : monthList)
    {
        if (!isInMonth(ev, m)) break;
        m.addEvent(ev);
    }
}

...

// Remove months that are not in scope from the front of the list.
// Add months that are in scope to the end of the list
public void shiftList(LinkedList<Month> monthList, Iterator<Month> i, Event ev)
{
    while(!monthList.size() > 0 && !isInMonth(ev, monthList.getFirst()))
    {
        monthList.removeFirst();
    }
    while(i.hasNext() && isInMonth(ev, monthList.getLast()))
    {
        monthList.addLast(i.next());
    }
}

, , : , , , . , , , , .

+1

Event Month? , :

for(Event event : events) {

   for(Month aMonth : myMonths) {

      if(aMonth >= event.startMonth && aMonth <= event.startMonth+event.duration) {
         aMonth.add(event);
      }

    }
}

, . , if(), , .

+2

The Google guava library provides PeekingIterator, which allows the use of a singleton peekahead. Create it through Iterators.peekingIterator(Iterator).

0
source

Source: https://habr.com/ru/post/1788640/


All Articles