View Javadoc

1   package com.diasparsoftware.java.util;
2   
3   import java.io.Serializable;
4   import java.math.BigDecimal;
5   
6   public class Quantity implements Serializable, Cloneable {
7       private static Object NULL_UNIT_OF_MEASURE = new Object();
8       public static Quantity ZERO = new Quantity(new BigDecimal(0), null);
9   
10      protected BigDecimal magnitude;
11      protected Object unitOfMeasure;
12  
13      public Quantity(Integer magnitude, Object unitOfMeasure) {
14          this(new BigDecimal(magnitude.toString()), unitOfMeasure);
15      }
16  
17      public Quantity(BigDecimal magnitude, Object unitOfMeasure) {
18          if (unitOfMeasure == null) {
19              this.unitOfMeasure = NULL_UNIT_OF_MEASURE;
20          }
21          this.magnitude = magnitude;
22          this.unitOfMeasure = unitOfMeasure;
23      }
24  
25      /***
26       * If you do not override clone(), then the add() operation
27       * will fail for subclasses of Quantity, returning a Quantity
28       * object rather than one of the specific subclass type.
29       */
30      public Object clone() {
31          return new Quantity(magnitude, unitOfMeasure);
32      }
33      
34      public Quantity add(Quantity that) {
35          if (this.unitOfMeasure.equals(that.unitOfMeasure) == false)
36              throw new ClassCastException(
37                  "Cannot add a ["
38                      + unitOfMeasure
39                      + "] and a ["
40                      + that.unitOfMeasure
41                      + "]");
42  
43          Quantity sum = (Quantity) this.clone();
44          sum.magnitude = sum.magnitude.add(that.magnitude);
45          
46          return sum;
47      }
48  
49      public boolean equals(Object other) {
50          if (other instanceof Quantity) {
51              Quantity that = (Quantity) other;
52              return this.magnitude.equals(that.magnitude)
53                  && this.unitOfMeasure.equals(that.unitOfMeasure);
54          }
55          else {
56              return false;
57          }
58      }
59      
60      public int hashCode() {
61          return magnitude.hashCode();
62      }
63  
64      public String toString() {
65          return "<" + magnitude + ", " + unitOfMeasure + ">";
66      }
67  
68      public static Quantity zeroOf(Object unitOfMeasure) {
69          return new Quantity(new BigDecimal(0), unitOfMeasure);
70      }
71  }