我可以使用哪个java集合?

我可以使用哪个java集合?,java,collections,dictionary,map,Java,Collections,Dictionary,Map,我需要存储一组数据结构,这些数据结构由时间段(开始、结束)和计数器定义,用于保存一些复杂的计算结果。数据结构的简化定义如下: public class CounterBag { private Period period; // collection key private Counter counter; // accessors // ... } 期间非常简单: public class Period { public DateTime star

我需要存储一组数据结构,这些数据结构由时间段(开始、结束)和计数器定义,用于保存一些复杂的计算结果。数据结构的简化定义如下:

public class CounterBag {
    private Period period;   // collection key
    private Counter counter;
    // accessors
    // ...
}
期间
非常简单:

public class Period {
    public DateTime start;
    public DateTime end;
    // accessors
    // ...
}
我需要一个集合,其中包含由不同的
时段定义的
计数器包
对象。 集合需要通过
longtimeinmillis
提供有效的查找(这里是关键!),因此
HashMap
不是一个真正的选项,因为我不想覆盖
CounterBag
equals
hashcode
(我需要两者)。集合需要按
期间
(按结束日期)排序<代码>周期
s具有灵活的持续时间,执行查找的零件不知道该持续时间

我想知道java标准API或某个开源库中是否有现成的集合可以帮助我解决这个问题?某种排序集或排序映射可以实现按日期的高效查找。按日期查找将返回一个
柜台包
,日期在
期间


谢谢你的建议

您可以使用TreeMap作为其排序集合(这使得查找效率更高)


如果你的周期有固定的间隔(这是最简单的形式),你就不需要这样的集合。您只需为每个间隔设置一个计数器即可。e、 g.a
int[]

我只想扩展@Peter Lawrey answer,使用树形图和定制的计数器比较器

该比较器将确保返回范围内的计数器袋


查找的效率取决于比较器的实现。

如果周期不重叠,我建议使用
TreeMap
。当您需要以毫秒为单位获取给定时间时,您可以使用以下命令:

// 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);
//初始化映射
Map Map=newtreemap();
地图。放置(…);
//准备“查询”
长时间单位毫秒=。。。;
期间fakePeriod=新期间(新日期(timeInMillis)、新日期(timeInMillis));
//在规定的时间内拿到行李。
柜台包=地图获取(伪造期);
在这种情况下,
Period
必须实现
compariable
,或者将自己的比较器传递到树。如果两个周期重叠,则比较结果应返回0(在我们的例子中,如果某个真实周期包括开始和结束时间等于
timeInMillis
)的假周期)。

我建议使用
TreeMap
。您可以使用
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's end is
 * less than or equal to the Long
 */
CounterBag newBag = map.floorEntry(lookupLong).getValue();
NavigableMap=newtreemap();
map.put(bag.period.end.toMillis(),bag);//将结束日期时间设置为长时间
long lookupLong=10000L;//或者别的什么
/*
*检索其周期结束时间为的最大包
*小于或等于长的
*/
CounterBag newBag=map.floorEntry(lookupLong.getValue();

由于任何可能的开始时间都可能符合条件,因此,给定足够的持续时间,按开始时间排序的简单ArrayList将是一种有效的方法,特别是在允许重叠的情况下(产生多个结果)。您只能迭代到第一条记录,其中开始时间>请求的时间单位为毫秒。

谢谢,问题是
期间的开始和结束是灵活的,执行查找的部分不知道,因此查找将按日期而不是按期间进行。