为什么指定BigDecimal.equals来单独比较值和比例? [英] Why is BigDecimal.equals specified to compare both value and scale individually?

查看:158
本文介绍了为什么指定BigDecimal.equals来单独比较值和比例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是不是关于如何比较两个的BigDecimal 对象的问题 - 我知道,你可以使用的compareTo 代替等于这样做,因为等于记录为:

This is not a question about how to compare two BigDecimal objects - I know that you can use compareTo instead of equals to do that, since equals is documented as:

不像的compareTo,这种方法仅考虑它们是否在值和标度相等的两个BigDecimal对象相等(当用这种方法比较由此2.0不等于2.00)。

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

问题是:为什么等于是以这种看似违反直觉的方式指定的?也就是说,为什么重要能够区分2.0和2.00?

The question is: why has the equals been specified in this seemingly counter-intuitive manner? That is, why is it important to be able to distinguish between 2.0 and 2.00?

似乎必须有这样的理由,由于 Comparable 文档(指定 compareTo 方法)指出:

It seems likely that there must be a reason for this, since the Comparable documentation, which specifies the compareTo method, states:

强烈建议(虽然不是必需的)使自然排序与equals一致

It is strongly recommended (though not required) that natural orderings be consistent with equals

我想象必须有忽略这一建议一个很好的理由。

I imagine there must be a good reason for ignoring this recommendation.

推荐答案

由于在某些情况下,的精度的指示(即误差幅度)可能很重要。

Because in some situations, an indication of precision (i.e. the margin of error) may be important.

例如,如果您存储由两个物理传感器进行的测量,那么一个传感器的精度可能比另一个高10倍。代表这一事实可能很重要。

For example, if you're storing measurements made by two physical sensors, perhaps one is 10x more precise than the other. It may be important to represent this fact.

这篇关于为什么指定BigDecimal.equals来单独比较值和比例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆