繁体   English   中英

实现与方法比较的Comparable接口的小部件类

[英]Widget class that implements the Comparable interface that compares to method

我假设存在实现Comparable接口的Widget类,因此有一个compareTo 方法 ,该方法接受Object参数并返回一个int值。 我想编写一个高效的静态方法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→
如果应为true,则为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时为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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM