I have a piece of code in Java where -
public boolean method1(Double d1, Double d2) {
if (d1.equals(d2)) {
//Some logic
return bool;
}
The statement d1.equals(d2) has a sonar violation which says that "Equality tests should not be made with floating point values." Link : https://rules.sonarsource.com/java/RSPEC-1244
In the explanation it talks about where using a == or === matters but since I'm using a equals method, why does it still show this up as a sonar violation?
CodePudding user response:
This has nothing to do with ==
versus equals
, and everything to do with how both double
and Double
(and float
and Float
) values are very difficult to ensure that they are exactly, 100% equal -- and not, say, different by 0.0000000000001.
Sonar is recommending that you do something like, say, Math.abs(d1 - d2) < 0.0000001
.
CodePudding user response:
I think the sonar violation is showing up, because you are invoking the equals method on two objects, which are most likely not the same.
However the Double class has solved this problem, by overwriting the equals method and just checking weather the two numbers contained in the object are equal. I just checked that in Java, just to be safe that it works. You can thus just ignore the warning.
Hope this helps. Kind regards, 403