如何比较两个JSR-363数量对象?

huangapple go评论91阅读模式
英文:

How to compare two JSR-363 Quantity objects?

问题

我试图使用JSR-363中的Quantity类来管理我的应用程序中的一些量值。我有一些类似下面的代码,我想将其转换为使用Quantity类的代码。

Double volume1 = 14d;
Double volume2 = 18d;

Assert.isTrue(volume1 < volume2);

使用Quantity,我正在尝试找到一种比较两个量值的方法,但在API中似乎没有与上述简单比较等效的内容!

Quantity<Volume> volume1 = Quantities.getQuantity(14d, Units.LITRE);
Quantity<Volume> volume2 = Quantities.getQuantity(18d, Units.LITRE);

// 在这里,断言volume1 < volume2;但是 < 运算符在这里不存在

我漏掉了什么?

英文:

I'm trying to use JSR-363 Quantity to manage some quantities in my application. I have some code similar to the following that I would like to convert to use the Quantity class.

Double volume1 = 14d;
Double volume2 = 18d;

Assert.isTrue(volume1 &lt; volume2);

Using Quantity, I'm trying to find a way to compare two volumes, but there doesn't seem to be anything in the API that's equivalent to the simple comparison above!

Quantity&lt;Volume&gt; volume1 = Quantities.getQuantity(14d, Units.LITRE);
Quantity&lt;Volume&gt; volume2 = Quantities.getQuantity(18d, Units.LITRE);

Assert.isTrue(volume1 &lt; volume2); &lt;--- operator &lt; doesn&#39;t exist

What am I missing?

答案1

得分: 1

&lt; 只适用于原始数值类型(以及装箱等价类型)。您不能将其用于对象。

请改用 volume1.substract(volume2).getValue().doubleValue() &lt; 0

英文:

&lt; only works with primitive number types (and boxed equivalents). You cannot use it with objects.

Use volume1.substract(volume2).getValue().doubleValue() &lt; 0 instead.

答案2

得分: 1

这表明现在有一个更新的度量单位规范以及一个提供了实现了 java.lang.Comparable 接口的 ComparableQuantity 类的参考实现。

这个更新的标准是 JSR-385,其参考实现是 Indriya

通过这个,可以执行以下操作:

ComparableQuantity<Volume> volume1 = Quantities.getQuantity(14d, Units.LITRE);
ComparableQuantity<Volume> volume2 = Quantities.getQuantity(18d, Units.LITRE);

Assert.isTrue(volume1.isGreaterThan(volume2));
Assert.isTrue(volume2.isLessThan(volume1));
英文:

It turns out that there's a newer specification for units of measurements and a reference implementation that provides ComparableQuantity class that implements java.lang.Comparable.

Then newer standard is JSR-385 and its reference implementation is Indriya.

With this one can do:

ComparableQuantity&lt;Volume&gt; volume1 = Quantities.getQuantity(14d, Units.LITRE);
ComparableQuantity&lt;Volume&gt; volume2 = Quantities.getQuantity(18d, Units.LITRE);

Assert.isTrue(volume1.isGreaterThan(volume2));
Assert.isTrue(volume2.isLessThan(volume1));

huangapple
  • 本文由 发表于 2020年8月17日 22:26:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63452928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定