java - 实现与方法比较的 Comparable 接口的 Widget 类
问题描述
我假设存在一个实现 Comparable 接口的 Widget 类,因此具有一个接受 Object 参数并返回 int的 compareTo方法。我想编写一个高效的静态方法 getWidgetMatch,它有两个参数。第一个参数是对 Widget 对象的引用。第二个参数是一个可能非常大的 Widget 对象数组,它已根据 Widget compareTo方法按升序排序。getWidgetMatch 根据equals方法在数组中查找与第一个参数匹配的元素,如果找到则返回true,否则返回false。
我将分享两个我几乎可以工作的代码以及我的调试错误。希望有人有我没有看到的答案。
代码 1:
public static boolean getWidgetMatch(Widget a, Widget[] b){
int bot=0;
int top=b.length-1;
int x = 0;
int y=0;
while (bot >= top)
{
x = (top + bot/2);
y = a.compareTo(b[x]);
if (y==0)
return true;
if (y<0)
top=x;
else
bot=x;
return false;
}
return a.equals(b[x]);
}
这个调试语句是这样的,[LWidget;@5305068a →<br> false 当它应该为真时。我可能错过了一个“>”标志吗?
代码 2:
public static boolean getWidgetMatch(Widget a, Widget[] b) {
for(int i =0;i<b.length;i++){
if(b[i].compareTo(a)== 0)return true;
}
return false;
}
这个调试语句是这样的,[LWidget;@5305068a → true 当它应该为真时,这是我对这段代码最困惑的地方。
我可能错过了“+”或“-”或“/”号吗?
谢谢。
解决方案
尝试这个:
public static boolean getWidgetMatch(Widget object, Widget[] wList){
int low = 0;
int high = wList.length - 1;
while(low <= high){
int middle = low + (high-low)/2;
if(object.compareTo(wList[middle]) < 0)
high = middle - 1;
else if(object.compareTo(wList[middle]) > 0)
low = middle + 1;
else
return true;
}
return false;
}
推荐阅读
- sqlite - 数据库中的目标行
- excel - 数据透视表 - 将付款合并为一个
- ffmpeg - 使用ffmpeg将两个通道转换为左或右的单个通道
- javascript - 单击提交按钮时如何更改数组的值而不清除之前所做的更改?
- sitefinity - 在页面上放置 Sitefinity 内容块
- jess - JESS 引擎的网页不可用
- windows - Set-Location 是否看到“遍历/执行”NTFS 权限?
- javascript - 通过javascript中的if语句向数组添加值
- woocommerce - Woocommerce:删除 function.php 中的“添加到购物车”按钮
- java - 如何单击 Selenium 中的嵌套链接