View Javadoc
1   package org.djutils.event.collection;
2   
3   import java.util.Iterator;
4   
5   import org.djutils.event.EventType;
6   import org.djutils.event.LocalEventProducer;
7   import org.djutils.exceptions.Throw;
8   import org.djutils.metadata.MetaData;
9   
10  /**
11   * The EventProducingIterator provides an iterator embedding the Iterator, which fires an event when an object has been removed.
12   * Note that one does not have to subscribe specifically to the events of the EventProducingIterator, as the EventProducing
13   * collection subscribes to the EventProducingIterator's remove events and fires these again to its subscribers.
14   * <p>
15   * Copyright (c) 2002-2025 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
16   * for project information <a href="https://djutils.org" target="_blank"> https://djutils.org</a>. The DJUTILS project is
17   * distributed under a three-clause BSD-style license, which can be found at
18   * <a href="https://djutils.org/docs/license.html" target="_blank"> https://djutils.org/docs/license.html</a>. This class was
19   * originally part of the DSOL project, see <a href="https://simulation.tudelft.nl/dsol/manual" target="_blank">
20   * https://simulation.tudelft.nl/dsol/manual</a>.
21   * </p>
22   * @author <a href="https://www.linkedin.com/in/peterhmjacobs">Peter Jacobs </a>
23   * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a>
24   * @param <T> the type of elements to iterate on
25   */
26  public class EventProducingIterator<T> extends LocalEventProducer implements Iterator<T>
27  {
28      /** OBJECT_REMOVED_EVENT is fired on removal of entries. */
29      public static final EventType OBJECT_REMOVED_EVENT = new EventType("OBJECT_REMOVED_EVENT", MetaData.NO_META_DATA);
30  
31      /** our parent iterator. */
32      private Iterator<T> wrappedIterator = null;
33  
34      /**
35       * constructs a new EventProducingIterator, embedding the parent Iterator.
36       * @param wrappedIterator parent.
37       */
38      public EventProducingIterator(final Iterator<T> wrappedIterator)
39      {
40          Throw.whenNull(wrappedIterator, "parent cannot be null");
41          this.wrappedIterator = wrappedIterator;
42      }
43  
44      @Override
45      public boolean hasNext()
46      {
47          return getWrappedIterator().hasNext();
48      }
49  
50      @Override
51      public T next()
52      {
53          return getWrappedIterator().next();
54      }
55  
56      @Override
57      public void remove()
58      {
59          getWrappedIterator().remove();
60          fireEvent(OBJECT_REMOVED_EVENT);
61      }
62  
63      /**
64       * Return the embedded iterator.
65       * @return the embedded iterator
66       */
67      protected Iterator<T> getWrappedIterator()
68      {
69          return this.wrappedIterator;
70      }
71  
72  }