java 二进制 对象_java – 为复合对象编写Comparator以进行二进制搜索

我有一个类和实例列表,看起来像这样(更改字段名称以保护无辜/专有):

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值