UnitsConversionUtil { public static int compare(String unitA, long valueA, String unitB, long valueB) { checkUnitArgument(unitA); checkUnitArgument(unitB); if (unitA.equals(unitB)) { return Long.compare(valueA, valueB); } Converter unitAC = getConverter(unitA); Converter unitBC = getConverter(unitB); int unitAPos = SORTED_UNITS.indexOf(unitA); int unitBPos = SORTED_UNITS.indexOf(unitB); try { long tmpA = valueA; long tmpB = valueB; if (unitAPos < unitBPos) { tmpB = convert(unitB, unitA, valueB); } else { tmpA = convert(unitA, unitB, valueA); } return Long.compare(tmpA, tmpB); } catch (IllegalArgumentException ie) { BigInteger tmpA = BigInteger.valueOf(valueA); BigInteger tmpB = BigInteger.valueOf(valueB); if (unitAPos < unitBPos) { tmpB = tmpB.multiply(BigInteger.valueOf(unitBC.numerator)); tmpB = tmpB.multiply(BigInteger.valueOf(unitAC.denominator)); tmpB = tmpB.divide(BigInteger.valueOf(unitBC.denominator)); tmpB = tmpB.divide(BigInteger.valueOf(unitAC.numerator)); } else { tmpA = tmpA.multiply(BigInteger.valueOf(unitAC.numerator)); tmpA = tmpA.multiply(BigInteger.valueOf(unitBC.denominator)); tmpA = tmpA.divide(BigInteger.valueOf(unitAC.denominator)); tmpA = tmpA.divide(BigInteger.valueOf(unitBC.numerator)); } return tmpA.compareTo(tmpB); } }  static long convert(String fromUnit, String toUnit, long fromValue); static int compare(String unitA, long valueA, String unitB,
      long valueB); static int compareUnits(String unitA, String unitB); static final Set<String> KNOWN_UNITS; }
@Test public void testCompare() { String unitA = "P"; long valueA = 1; String unitB = "p"; long valueB = 2; Assert.assertEquals(1, UnitsConversionUtil.compare(unitA, valueA, unitB, valueB)); Assert.assertEquals(-1, UnitsConversionUtil.compare(unitB, valueB, unitA, valueA)); Assert.assertEquals(0, UnitsConversionUtil.compare(unitA, valueA, unitA, valueA)); Assert.assertEquals(-1, UnitsConversionUtil.compare(unitA, valueA, unitA, valueB)); Assert.assertEquals(1, UnitsConversionUtil.compare(unitA, valueB, unitA, valueA)); unitB = "T"; Assert.assertEquals(1, UnitsConversionUtil.compare(unitA, valueA, unitB, valueB)); Assert.assertEquals(-1, UnitsConversionUtil.compare(unitB, valueB, unitA, valueA)); Assert.assertEquals(0, UnitsConversionUtil.compare(unitA, valueA, unitB, 1000L)); unitA = "p"; unitB = "n"; Assert.assertEquals(-1, UnitsConversionUtil.compare(unitA, valueA, unitB, valueB)); Assert.assertEquals(1, UnitsConversionUtil.compare(unitB, valueB, unitA, valueA)); Assert.assertEquals(0, UnitsConversionUtil.compare(unitA, 1000L, unitB, valueA)); }