次のようなクラスとインスタンスのリストがあります (フィールド名は無実/独自のものを保護するために変更されています):
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
(そして、番号が2つのレコードの間にある場合、前のレコードを見つけたい)
これを機能させるために一連の 3 つの Comparator クラスを作成する最も簡単な方法は何ですか? 探していないものにダミー フィールドを持つ Bloat オブジェクトであるキーを使用する必要がありますか?