Vidya Ramanarayanan
Vidya Ramanarayanan

Reputation: 167

Sonar violation in Java on DoubleValue.equals(AnotherDoubleValue) - Why?

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?

Upvotes: 0

Views: 382

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198211

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.

Upvotes: 5

Log4JExploit
Log4JExploit

Reputation: 5

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

Upvotes: -3

Related Questions