繁体   English   中英

我可以使用哪个java集合?

[英]Which java collection can I use?

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

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

Period很简单:

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

我需要一个包含不同Periods定义的CounterBag对象的集合。 该集合需要通过long timeInMillis提供有效的查找(这里是catch!),因此HashMap实际上不是一个选项,因为我不想覆盖CounterBag equalshashcode (我需要它们)。 集合需要按Period (按结束日期)排序。 Period s具有灵活的持续时间,这对于将执行查找的部分是未知的。

我想知道java标准API或某些开源库中是否有开箱即用的集合可以帮助我解决它? 某种排序集或排序映射,可以按日期实现有效查找。 按日期查找将返回一个CounterBag其中Period包含日期。

感谢您的建议。

您可以使用TreeMap作为Sorted集合(这使查找更有效)

如果您的句点有规律的间隔(这是最简单的形式),您不需要这样的集合。 你可以为每个间隔设置一个计数器。 例如一个int[]

我只想扩展@Peter Lawrey的答案,使用TreeMap和CounterBag的自定义比较器。

该比较器将确保返回落在该范围内的CounterBag。

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

如果句点不重叠,那么我建议使用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或者将自己的比较器传递给树。 如果它们重叠,则2个句点的比较应该返回0(在我们的例子中,如果某个实际句点包括我们的假期,其开始和结束时间等于timeInMillis )。

我建议使用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's end is
 * less than or equal to the Long
 */
CounterBag newBag = map.floorEntry(lookupLong).getValue();

因为可能任何开始时间都有资格,给定足够的持续时间,按开始时间排序的简单ArrayList将是一种有效的方法,特别是如果允许重叠(产生多个结果)。 您只会迭代到开始时间>请求timeInMillis的第一条记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM