我有一个类和实例列表,看起来像这样(更改了字段名称以保护无辜/专有):
public class Bloat
{
public long timeInMilliseconds;
public long spaceInBytes;
public long costInPennies;
}
public class BloatProducer
{
final private List<Bloat> bloatList = new ArrayList<Bloat>();
final private Random random = new Random();
public void produceMoreBloat()
{
int n = bloatList.size();
Bloat previousBloat = (n == 0) ? new Bloat() : bloatList.get(n-1);
Bloat newBloat = new Bloat();
newBloat.timeInMilliseconds =
previousBloat.timeInMilliseconds + random.nextInt(10) + 1;
newBloat.spaceInBytes =
previousBloat.spaceInBytes + random.nextInt(10) + 1;
newBloat.costInPennies =
previousBloat.costInPennies + random.nextInt(10) + 1;
bloatList.add(newBloat);
}
/* other fields/methods */
public boolean testMonotonicity()
{
Bloat previousBloat = null;
for (Bloat thisBloat : bloatList)
{
if (previousBloat != null)
{
if ((previousBloat.timeInMilliseconds
>= thisBloat.timeInMilliseconds)
|| (previousBloat.spaceInBytes
>= thisBloat.spaceInBytes)
|| (previousBloat.costInPennies
>= thisBloat.costInPennies))
return false;
}
previousBloat = thisBloat;
}
return true;
}
BloatProducer bloatProducer;
该列表bloatList
由内部保存BloatProducer
并以这样的方式维护:它只附加新Bloat
记录,不修改任何旧记录,并且每个字段都是单调递增的,例如bloatProducer.testMonotonicity()
总是返回true
。
我想使用timeInMilliseconds、spaceInBytes 或 costInPennies 字段Collections.binarySearch(list,key,comparator)
来搜索记录。Bloat
(如果数字在两条记录之间,我想找到上一条记录)
编写一系列 3 个比较器类以使其工作的最简单方法是什么?我是否必须使用带有虚拟字段的 Bloat 对象作为我不搜索的键?