2

This question comes after this piece of code (an implementation of binary search). I would appreciate if someone could tell me why this is not outputting the expected answer:

public static void main(String[] args){
    Double[] array = {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0};
    BinarySearch s = new BinarySearch(array);
    System.out.println(s.searchNextHighest(2.0));
}

public BinarySearch(Double[] array){
    numbers = array;
}

public Integer searchNextHighest(Double y){
    return binarySearchNextHighest(0, numbers.length-1, y, numbers);
}

public Integer binarySearchNextHighest(int min, int max, Double target, Double[] array){
    int mid = (min+max)/2;

    if(target==array[mid]){ //Fails here
        return mid;
    }

    if(max<min){
        if(min>=array.length) return null;
        return mid;
    }

    if(target>array[mid]){
        return binarySearchNextHighest(mid+1, max, target, array);
    }else{
        return binarySearchNextHighest(min, mid-1, target, array);
    }
}

Output: 1

I followed through a debugger and made absolute sure. At a certain moment, target = 2.0, and mid=2, and array[mid] = 2.0. Yet the if statement does not execute.

Curiously, this error does not occur when Integer arrays/targets are used.

What is happening here? I thougt these things only happened when comparing very big numbers. What other pitfalls exist?

[EDIT] Here is a simplified version:

public static void main(String[] args){
    Double[] array = {2.0};
    Double target = 2.0;
    if(array[0] == target) System.out.println("Yay!");
}

Output: None

[EDIT2]

public static void main(String[] args){
    double[] array = {3.0};
    double target = 3.0;
    if(array[0] == target) System.out.println("Yay!");
}

Output: Yay!

Someone in comments pointed out that this error was a result of comparing objects. Why isn't it automatically unpacking?

[EDIT3] Here is code using the Integer object:

public static void main(String[] args){
    Integer[] array = {3};
    Integer target = 3;
    if(array[0] == target) System.out.println("Yay!");
}

Output: Yay!

So I guess the reason is obvious, but why is the object Integer implemented so differently? That is automatically unpacks itself.

4

2 回答 2

6

doubleDouble是两个不同的东西。Double创建一个对象,如果它们指向内存中的相同地址,它们将相等。它们持有的值可以相同,但它们是不同的对象,因此不相等。与 相同Integer。对于您的代码,您可以double改用或比较通过.doubleValue().equals()方法Double来比较值。

编辑:正如@MarkPeters 和@TedHopp 在评论中指出的那样,Integer行为有点不同,更多信息在这里

于 2013-08-26T04:40:07.840 回答
3

使用该equals()方法比较两个对象的内容。

 if(target.equals(array[mid])){
    return mid;
}  

根据Double#equals

将此对象与指定对象进行比较。当且仅当参数不为 null 并且是一个 Double 对象,该对象表示一个与该对象表示的双精度具有相同值的双精度时,结果才为真。

另请查看“.equals”和“==”有什么区别?

于 2013-08-26T04:38:33.833 回答