1

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?

Mustafa
  • 5,624
  • 3
  • 24
  • 40

2 Answers2

1

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

Use volume1.substract(volume2).getValue().doubleValue() < 0 instead.

VGR
  • 40,506
  • 4
  • 48
  • 63
  • Thank you. I was looking for something like `volume1.compare(volume2)` in the API, but this has to do for now I guess. – Mustafa Aug 18 '20 at 02:37
1

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));
Mustafa
  • 5,624
  • 3
  • 24
  • 40
  • 1
    Very interesting. I’m glad to know the Units API has been revived! But it appears ComparableQuantity is implementation specific and is not a part of the API. – VGR Aug 22 '20 at 17:13