1 package org.apidesign.apifest08.currency;
3 import java.math.BigDecimal;
4 import java.util.Currency;
7 * An amount of a currency.
11 public class MonetaryAmount {
13 private final BigDecimal amount;
14 private final Currency currency;
18 * @param amount the quantity of the currency; must not be null
19 * @param currency the currency; must not be null
21 public MonetaryAmount( final BigDecimal amount, final Currency currency ) {
23 this.currency = currency;
24 if ( amount == null ) {
25 throw new NullPointerException( "The amount" );
27 if ( currency == null ) {
28 throw new NullPointerException( "The currency" );
34 * @param amount the quantity of the currency; must not be null
35 * @param currency the currency; must not be null
37 public MonetaryAmount( final double amount, final Currency currency ) {
38 this( new BigDecimal( amount ), currency );
45 public BigDecimal getAmount() {
51 * @return the currency
53 public Currency getCurrency() {
58 * The string representation of the monetary amount.
59 * @return the amount, a non-breakable space, the currency
62 public String toString() {
63 return amount.toPlainString() + "\u00a0" + currency.toString();
67 * Two monetary amounts are equal to each other iff they have equal amounts of equal currencies.
68 * @param other the other object
72 public boolean equals( final Object other ) {
73 if ( other instanceof MonetaryAmount ) {
74 final MonetaryAmount otherMonetaryAmount = (MonetaryAmount) other;
75 return getAmount().equals( otherMonetaryAmount.getAmount() ) && getCurrency().equals( otherMonetaryAmount.getCurrency() );
81 * The hash code combines the hash codes of the amount and of the currency.
85 public int hashCode() {
86 return amount.hashCode() * 37 + currency.hashCode();