在DoubleValue上违反Sonar违规。Equals(另一个DoubleValue) - 为什么?
我在Java中有一个代码,其中 -
public boolean method1(Double d1, Double d2) {
if (d1.equals(d2)) {
//Some logic
return bool;
}
语句D1。equals(d2)有声纳违规,上面说“不应使用浮点值进行平等测试”。链接: https://rules.sonarsource.com/java/java/rspec-1244
它谈到了使用a ==或===的解释很重要,但是由于我使用了平等方法,为什么它仍然将其显示为违规的声纳呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与
==
vors等于
,以及与double> double
和double
((float
和float
)值很难确保它们完全相等,而不是0.0000000000001。Sonar建议您做类似
Math.abs(D1 -D2)&lt< 0.0000001
。This has nothing to do with
==
versusequals
, and everything to do with how bothdouble
andDouble
(andfloat
andFloat
) 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
.我认为声纳违规正在出现,因为您在两个物体上调用 equals 方法,这很可能不是相同的。
但是, double 类通过覆盖 equals 方法,仅检查天气,对象中包含的两个数字是相等的。
我只是在Java检查了一下,只是为了安全起见。因此,您可以忽略警告。
希望这会有所帮助。
亲切的问候,
403
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