简体   繁体   English

java:d​​ouble ==和Double等于

[英]java: double == and Double equals

I am confused on a few things regarding using double. 我对使用double感到有些困惑。

  1. If i were to initialize 2 doubles with the same literal, would == always evaluate to true? 如果我要使用相同的字面量初始化2个双打,==总是会评估为true? for example, if following outputs true but i don't know if this is by chance: 例如,如果以下输出为真,但我不知道这是否是偶然的:

     double a = .1d; double b = .1d; System.out.println(a==b); 
  2. I get the same result when using Double instead of double: 当使用Double而不是double时,我得到相同的结果:

     Double a = .1d; Double b = .1d; System.out.println(a.equals(b)); 

According to Double documentation, equals() return true if doubleValue() are equal. 根据Double文档,如果doubleValue()相等,则equals()返回true。

So the question is, is "==" for double and "equals()" for Double guaranteed to evaluate to true for 2 variables initialized using the same literal? 因此,问题是,对于使用相同文字初始化的2个变量,是否保证对Double等于“ ==“,对Double等于” equals()”?

When would they evaluate to false? 他们什么时候会得出错误的结论? Is this when arithmetic operations are involved? 当涉及算术运算时,这是吗?

Thanks 谢谢

In general == is an operator which checks for equality. 通常, ==是用于检查相等性的运算符。 Object variables are references so it checks for reference or address equality. 对象变量是引用,因此它检查引用或地址是否相等。 In the case of primitive data types representing values in the memory that also means that it checks for value equality. 对于表示内存中值的原始数据类型,这也意味着它检查值的相等性。

The method equals(~) checks for value or content equality. equals(~)方法检查值或内容是否相等。 You do not use it for primitive data types but for Objects. 您不将其用于原始数据类型,而是用于对象。

That is also the case for double and Double. double和Double也是如此。 The problem which is arising with doubles is the mismatch of the values induced by rounding errors. 由双精度引起的问题是由舍入误差引起的值的不匹配。

Some arithmetic operations may handle rounding differently so you might get false for value equality even if you think it should be equal. 一些算术运算可能会以不同的方式处理舍入,因此即使您认为值相等,对于值相等也可能会false

It should be stated that even if the rounding rules are a bit inconsistent arithmetic operations are deterministic so that inconsistency can be handled. 应该指出,即使舍入规则有点不一致,算术运算也是确定的,这样就可以处理不一致的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM