Comparing doubles in Java gives odd results

前端 未结 5 780
误落风尘
误落风尘 2021-02-05 16:54

I really can\'get my head around why the following happens:

Double d = 0.0;
System.out.println(d == 0); // is true
System.out.println(d.equals(0)); // is false ?         


        
5条回答
  •  离开以前
    2021-02-05 17:51

    Number objects only equal to numbers with the same value if they are of the same type. That is:

    new Double(0).equals(new Integer(0));
    new BigInteger("0").equals(new BigDecimal("0"));
    

    and similar combinations are all false.

    In your case, the literal 0 is boxed into an Integer object.

提交回复
热议问题