【问题标题】:Widget class that implements the Comparable interface that compares to method实现与方法比较的 Comparable 接口的 Widget 类
【发布时间】:2019-01-15 06:33:11
【问题描述】:

我假设存在一个实现 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 →
当它应该是真的时是假的。我可能错过了一个“>”标志吗?

代码 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 → 当它应该为真时为真,这是我对这段代码最困惑的地方。

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

谢谢。

【问题讨论】:

    标签: java class methods widget implements


    【解决方案1】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      相关资源
      最近更新 更多