2 **********************************************************************
3 * Copyright (c) 2004-2013, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
7 * Created: April 20, 2004
9 **********************************************************************
11 package com.ibm.icu.util;
15 * An amount of a specified unit, consisting of a Number and a Unit.
16 * For example, a length measure consists of a Number and a length
17 * unit, such as feet or meters. This is an abstract class.
18 * Subclasses specify a concrete Unit type.
20 * <p>Measure objects are parsed and formatted by subclasses of
23 * <p>Measure objects are immutable. All subclasses must guarantee that.
25 * @see java.lang.Number
26 * @see com.ibm.icu.util.MeasureUnit
27 * @see com.ibm.icu.text.MeasureFormat
31 public class Measure {
33 private final Number number;
35 private final MeasureUnit unit;
38 * Constructs a new object given a number and a unit.
39 * @param number the number
40 * @param unit the unit
43 public Measure(Number number, MeasureUnit unit) {
44 if (number == null || unit == null) {
45 throw new NullPointerException();
52 * Returns true if the given object is equal to this object.
53 * @return true if this object is equal to the given object
56 public boolean equals(Object obj) {
57 if (obj == null) return false;
58 if (obj == this) return true;
60 Measure m = (Measure) obj;
61 return unit.equals(m.unit) && numbersEqual(number, m.number);
62 } catch (ClassCastException e) {
68 * See if two numbers are identical or have the same double value.
70 * @param b Another number to be compared with
71 * @return Returns true if two numbers are identical or have the same double value.
73 // TODO improve this to catch more cases (two different longs that have same double values, BigDecimals, etc)
74 private static boolean numbersEqual(Number a, Number b) {
78 if (a.doubleValue() == b.doubleValue()) {
85 * Returns a hashcode for this object.
86 * @return a 32-bit hash
89 public int hashCode() {
90 return number.hashCode() ^ unit.hashCode();
94 * Returns a string representation of this object.
95 * @return a string representation consisting of the ISO currency
96 * code together with the numeric amount
99 public String toString() {
100 return number.toString() + ' ' + unit.toString();
104 * Returns the numeric value of this object.
105 * @return this object's Number
108 public Number getNumber() {
113 * Returns the unit of this object.
114 * @return this object's Unit
117 public MeasureUnit getUnit() {