Java – comparison of positive and negative zeros

Why is java inconsistent when comparing - 0.0 and 0.0? What is the Java standard way to compare numbers to - 0 / 0?

I have encountered this particular bug Aboo:

public class ZeroCompare {
    public static void main(String[] args) {
        if ( 0.0 == -0.0 ) {
            System.out.println("== --> same");
        } else {
            System.out.println("== --> different");
        }

        if ( new Double(0.0).equals( -0.0 ) ) {
            System.out.println("equals --> same");
        } else {
            System.out.println("equals --> different");
        }
    }
}

It prints the following:

== --> same
equals --> different

I don't like the fact that how you compare these two values will affect the results. I like to explain

Solution

This behavior is actually documented:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>