Custom iterable intervals using manually written iterators
If your items are not sequenceable, you can make an iterable interval class for those items, but you write more code to implement all necessary methods.
Create a custom iterable interval using manually written iterator classes
You perform the following general tasks to write a manual iterator class.
- Confirm that the type of items
in your interval implement the Java interface
java.lang.Comparable. - Create a new class that extends (is a subclass of) the
IterableInterval class parameterized using Gosu generics
across four separate dimensions:
- The type of each element in the interval
- The type of the step amount. For
example, to skip every other item, the step is 2, which is an
Integer. - The type of units for the interval.
For example, for an integer (1, 2, 3), choose
Integer. For a date interval, the type isDateUnit.That type contains values representing days, weeks, or months. For instance,DateUnit.DAYS. If the interval does not have units, usejava.lang.Voidfor this dimension of the parameterization. Make sure that you use the capitalization of this type. In Gosu, as in Java,java.lang.Voidis the special type of the valuenull. - The type of your custom interval. This type is self-referential because some of the methods return an instance of the interval type itself.
The documentation provides an example of a class that extends the type:
IterableInterval<Color, Integer, void, ColorInterval> - Implement the interface methods for the
Intervalinterface. - Implement the interface methods for the
Iterableinterface.The most complex methods to implement correctly are methods that return iterators. A straightforward way to implement these methods is to define iterator classes as inner classes to your main class.
Your class must be able to return two types of iterators, one iterating forward, and one iterating in reverse. One way to do this is to implement a main iterator. Next, implement a class that extends your main iterator class, and which operates in reverse. On the class for the reverse iterator, to reverse the behavior you may need to override only the
hasNextand next methods.
See also
