Java signed zero and boxing

后端 未结 3 1865
面向向阳花
面向向阳花 2020-12-09 02:09

Lately I\'ve written a project in Java and noticed a very strange feature with double/Double implementation. The double type in Java has two 0\'s, i.e. 0.0 and -0.0 (signed

3条回答
  •  醉梦人生
    2020-12-09 02:51

    It important to undertand the use of signed zero in the Double class. (Loads of experienced Java programmers don't).

    The short answer is that (by definition) "-0.0 is less than 0.0" in all the methods provided by the Double class (that is, equals(), compare(), compareTo(), etc)

    Double allows all floating point numbers to be "totally ordered on a number line". Primitives behave the way a user will think of things (a real world definition) ... 0d = -0d

    The following snippets illustrate the behaviour ...

    final double d1 = 0d, d2 = -0d;
    
    System.out.println(d1 == d2); //prints ... true
    System.out.println(d1 < d2);  //prints ... false
    System.out.println(d2 < d1);  //prints ... false
    System.out.println(Double.compare(d1, d2)); //prints ... 1
    System.out.println(Double.compare(d2, d1)); //prints ... -1
    

    There are other posts that are relevant and nicely explain the background ...

    1: Why do floating-point numbers have signed zeros?

    2: Why is Java's Double.compare(double, double) implemented the way it is?

    And a word of caution ...

    If you don't know that, in the Double class, "-0.0 is less than 0.0", you may get caught out when using methods like equals() and compare() and compareTo() from Double in logic tests. For example, look at ...

    final double d3 = -0d; // try this code with d3 = 0d; for comparison
    
    if (d3 < 0d) {     
        System.out.println("Pay 1 million pounds penalty");
    } else {           
        System.out.println("Good things happen"); // this line prints
    }
    
    
    if (Double.compare(d3, 0d) < 0) { //use Double.compare(d3, -0d) to match the above behaviour
        System.out.println("Pay 1 million pounds penalty"); // this line prints
    } else {                              
        System.out.println("Good things happen"); 
    }
    

    and for equals you might try ... new Double(d3).equals(0d) || new Double(d3).equals(-0d)

提交回复
热议问题