首页 > 解决方案 > 实现与方法比较的 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 当它应该为真时,这是我对这段代码最困惑的地方。

我可能错过了“+”或“-”或“/”号吗?

谢谢。

标签: javaclassmethodswidgetimplements

解决方案


尝试这个:

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;
}

推荐阅读