我有一个类和实例列表,看起来像这样(更改字段名称以保护无辜/专有):
public class Bloat
{
public long timeInMilliseconds;
public long spaceInBytes;
public long costInPennies;
}
public class BloatProducer
{
final private List bloatList = new ArrayList();
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.
我想使用Collections.binarySearch(列表,键,比较器)通过timeInMilliseconds,spaceInBytes或costInPennies字段搜索Bloat记录. (如果数字在两个记录之间,我想找到以前的记录)
编写一系列3个Comparator类以使其工作的最简单方法是什么?我是否必须使用一个具有虚拟字段的Bloat对象的密钥用于我不搜索的密钥?
解决方法:
您需要为要比较的每个字段编写单独的比较器:
public class BloatTimeComparator implements Comparator {
public int compare(Bloat bloat1, Bloat bloat2) {
if (bloat1.timeInMilliseconds > bloat2.timeInMilliseconds) {
return 1;
} else if (bloat1.timeInMilliseconds < bloat2.timeInMilliseconds) {
return -1;
} else {
return 0;
}
}
}
对于你想比较的Bloat中的每个属性等等(你需要为每个属性创建一个比较器类).然后使用Collections帮助器方法:
Collections.binarySearch(bloatList, bloatObjectToFind,
new BloatTimeComparator());
从Java documentation for binarySearch方法,返回值将是:
the index of the search key, if it is contained in the list; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
您指定的索引是哪个.
标签:java,comparator,binary-search
来源: https://codeday.me/bug/20190610/1214683.html