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

后端 未结 4 1162
情书的邮戳
情书的邮戳 2020-12-01 03:26

I was looking at the implementation of compare(double, double) in the Java standard library (6). It reads:

public static int compare(double d1, double d2) {
         


        
4条回答
  •  难免孤独
    2020-12-01 04:00

    @Shoover's answer is correct (read it!), but there is a bit more to it than this.

    As the javadoc for Double::equals states:

    "This definition allows hash tables to operate properly."

    Suppose that the Java designers had decided to implement equals(...) and compare(...) with the same semantics as == on the wrapped double instances. This would mean that equals() would always return false for a wrapped NaN. Now consider what would happen if you tried to use a wrapped NaN in a Map or Collection.

    List l = new ArrayList();
    l.add(Double.NaN);
    if (l.contains(Double.NaN)) {
        // this wont be executed.
    }
    
    Map m = new HashMap();
    m.put(Double.NaN, "Hi mum");
    if (m.get(Double.NaN) != null) {
        // this wont be executed.
    }
    

    Doesn't make a lot of sense does it!

    Other anomalies would exist because -0.0 and +0.0 have different bit patterns but are equal according to ==.

    So the Java designers decided (rightly IMO) on the more complicated (but more intuitive) definition for these Double methods that we have today.

提交回复
热议问题