Listing 3-1 shows a test driver for a TimeSeries
class. The class is parameterized, the parameter being the object type of the event that is moving through time. In this program, that type is String
.
An array of six strings is defined at line 11. These will be the events to be loaded into the series
object that is instantiated at line 14. The loading is done by the load()
, defined at lines 27-31 and invoked at line 15.
The contents of the series are loaded at line 15. Then at lines 17-21, the six key-value pairs are printed. Finally, at lines 23-24, we use the direct access capability of the ArrayList
class to examine the series entry at index 3 (the fourth element). The output is shown in Figure 3-11.
Notice that the list's element type is TimeSeries.Entry
. That is a static
nested class, defined inside the TimeSeries
class, whose instances represent the key-value pairs.
The actual TimeSeries
class is shown in Listing 3-2:
The two folded code blocks at lines 43 and 61 are shown in Listing 3-3 and Listing 3-4.
Line 15 shows that the time series data is stored as key-value pairs in a TreeMap
object, with Long
for the key type and T
as the value type. The keys are long
integers that represent time. In the test program (Listing 3-1), we used String
for the value type T
.
The add()
method puts the specified time and event pair into the backing map at line 18, and then pauses for one microsecond at line 20 to avoid coincident clock reads. The call to sleep()
throws an InterruptedException
, so we have to enclose it in a try-catch
block.
The get()
method returns the event obtained from the corresponding map.get()
call at line 27.
The getList()
method returns an ArrayList
of all the key-value pairs in the series. This allows external direct access by index number to each pair, as we did at line 23 in Listing 3-1. It uses a for each
loop, backed by an Iterator
object, to traverse the series (see Listing 3-3). The objects in the returned list have type TimeSeries.Entry
, the nested class as shown in Listing 3-4.
The TimeSeries
class implements Iterable<TimeSeries.Entry>
(Listing 3-2, line 14). That requires the iterator()
method to be defined, as shown in Listing 3-3. It works by using the corresponding iterator defined on the backing map's key set (line 45).
Listing 3-4 shows the Entry
class, nested inside the TimeSeries
class. Its instances represent the key-value pairs that are stored in the time series.