1 9 package javax.measure.quantities; 10 11 import java.io.Serializable ; 12 13 import javax.measure.converters.UnitConverter; 14 import javax.measure.units.Unit; 15 16 25 public class Scalar<Q extends Quantity> extends Number implements Quantity<Q>, 26 Comparable <Quantity<Q>>, Serializable { 27 28 31 private double _amount; 32 33 36 private Unit<Q> _unit; 37 38 45 public Scalar(double amount, Unit<Q> unit) { 46 _amount = amount; 47 _unit = unit; 48 } 49 50 55 public final double getAmount() { 56 return _amount; 57 } 58 59 64 public final Unit<Q> getUnit() { 65 return _unit; 66 } 67 68 public final double doubleValue(Unit<Q> unit) { 70 if (unit == _unit) 71 return _amount; 72 UnitConverter cvtr = _unit.getConverterTo(unit); 73 return cvtr.convert(_amount); 74 } 75 76 public final long longValue(Unit<Q> unit) throws ArithmeticException { 78 double doubleValue = doubleValue(unit); 79 if ((doubleValue >= Long.MIN_VALUE) && (doubleValue <= Long.MAX_VALUE)) 80 return Math.round(doubleValue); 81 throw new ArithmeticException (doubleValue + " " + unit 82 + " cannot be represented as long"); 83 } 84 85 94 public int compareTo(Quantity<Q> that) { 95 double thatValue = that.doubleValue(_unit); 96 if (this._amount < thatValue) { 97 return -1; 98 } else if (this._amount > thatValue) { 99 return 1; 100 } else { 101 long l1 = java.lang.Double.doubleToLongBits(this._amount); 102 long l2 = java.lang.Double.doubleToLongBits(thatValue); 103 return (l1 == l2 ? 0 : (l1 < l2 ? -1 : 1)); 104 } 105 } 106 107 114 public final int intValue() { 115 return (int) getAmount(); 116 } 117 118 125 public final long longValue() { 126 return (long) getAmount(); 127 } 128 129 136 public final float floatValue() { 137 return (float) getAmount(); 138 } 139 140 146 public final double doubleValue() { 147 return getAmount(); 148 } 149 150 157 public boolean equals(Object that) { 158 return (that instanceof Scalar) 159 && (this._amount == ((Scalar) that)._amount); 160 } 161 162 167 public int hashCode() { 168 int h = Float.floatToIntBits((float) _amount); 169 h += ~(h << 9); 170 h ^= (h >>> 14); 171 h += (h << 4); 172 return h ^ (h >>> 10); 173 } 174 175 private static final long serialVersionUID = 1L; 176 } | Popular Tags |