英文:
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 < 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<Volume> volume1 = Quantities.getQuantity(14d, Units.LITRE);
Quantity<Volume> volume2 = Quantities.getQuantity(18d, Units.LITRE);
Assert.isTrue(volume1 < volume2); <--- operator < doesn't exist
What am I missing?
答案1
得分: 1
<
只适用于原始数值类型(以及装箱等价类型)。您不能将其用于对象。
请改用 volume1.substract(volume2).getValue().doubleValue() < 0
。
英文:
<
only works with primitive number types (and boxed equivalents). You cannot use it with objects.
Use volume1.substract(volume2).getValue().doubleValue() < 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<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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论