What java collection can i use?

I need to save a set of data structures that are determined by a period of time (beginning, end) and a counter for this period, which contains some complex calculation results. A simplified definition of the data structure is as follows:

public class CounterBag {
    private Period period;   // collection key
    private Counter counter;
    // accessors
    // ...
}

the Periodas simple as:

public class Period {
    public DateTime start;
    public DateTime end;
    // accessors
    // ...
}

, CounterBag, Periods. ( !) long timeInMillis, HashMap , equals hashcode CounterBag ( ). Period ( ). Period , , .

, API Java - , ? - , . CounterBag Period, .

.

+3
5

TreeMap ( )

( ), . . a int[]

0

@Peter Lawrey , TreeMap CounterBag.

, CounterBag, , .

.

0

, TreeMap<Period, CounterBag>. CounterBag , :

// Initialize map
Map<Period, CounterBag> map = new TreeMap<Period, CounterBag>();
map.put(...);

// Prepare "query"
long timeInMillis = ...;
Period fakePeriod = new Period(new Date(timeInMillis), new Date(timeInMillis));

// Get bag for given time.
CounterBag bag = map.get(fakePeriod);

Period Comparable, . 0, ( , , timeInMillis).

0

TreeMap<Long, CounterBag>. NavigableMap:

NavigableMap<Long, CounterBag> map = new TreeMap<Long, CounterBag>();
map.put(bag.period.end.toMillis(), bag); // Get end DateTime as a Long


long lookupLong = 10000L; // or whatever

/*
 * Retrieves the greatest Bag whose Period end is
 * less than or equal to the Long
 */
CounterBag newBag = map.floorEntry(lookupLong).getValue();
0

Since potentially any start time can be qualified, given sufficient time, a simple ArrayList sorted by start time will be an effective approach, especially if overlaps are possible (leading to multiple results). You will iterate only until the first record, where the start time> timeInMillis is requested.

0
source

All Articles