ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Apples and Oranges (and the Java Units Specification)
Subject:   JMeasure
Date:   2004-01-10 05:27:49
From:   michelsantos
Another implementation for tracking measurements is called JMeasure and is available online at http://jmeasure.dev.java.net It is open-sourced and available under the Academic Free License (http://opensource.org/licenses/academic.php) The "File Sharing" section contains the source code and a tutorial.


JMeasure represents a generic interface for measurement representation and arithmetic. It includes two concrete implementations oriented around physical units such as length, time, etc.


The example below demonstrates creating some measurements, performing arithmetic, and checking of "compatibility".



// 65 kph
Measurement speed = new Kilometer(65).div(new Hour());
System.out.println("Speed: " + speed);


// Measure the speed in terms of 5 cm/s
Measurement specialSpeed = new Centimeter(5).div(new Second());
System.out.println("5 cm/s: " + specialSpeed);
double value = speed.getValue(specialSpeed);
System.out.println("Speed as multiple of 5 cm/s: " + value);



... which produces the following output ...


Speed: 18.055555555555557 [ Length^1.0 Time^-1.0 ]
5 cm/s: 0.05 [ Length^1.0 Time^-1.0 ]
Speed as multiple of 5 cm/s: 361.11111111111114



Internally, these two implementations store values as multiples of SI units (meters, seconds, etc.), but other implementations are free to store the values in any other form, thus leaving the interface capable of dealing with such measurements as currency.