1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/task3/solution07/src/org/apidesign/apifest08/currency/MonetaryAmount.java Tue Oct 07 11:05:34 2008 +0200
1.3 @@ -0,0 +1,89 @@
1.4 +package org.apidesign.apifest08.currency;
1.5 +
1.6 +import java.math.BigDecimal;
1.7 +import java.util.Currency;
1.8 +
1.9 +/**
1.10 + * An amount of a currency.
1.11 + * Immutable.
1.12 + * @author jdvorak
1.13 + */
1.14 +public class MonetaryAmount {
1.15 +
1.16 + private final BigDecimal amount;
1.17 + private final Currency currency;
1.18 +
1.19 + /**
1.20 + * A new amount.
1.21 + * @param amount the quantity of the currency; must not be null
1.22 + * @param currency the currency; must not be null
1.23 + */
1.24 + public MonetaryAmount( final BigDecimal amount, final Currency currency ) {
1.25 + this.amount = amount;
1.26 + this.currency = currency;
1.27 + if ( amount == null ) {
1.28 + throw new NullPointerException( "The amount" );
1.29 + }
1.30 + if ( currency == null ) {
1.31 + throw new NullPointerException( "The currency" );
1.32 + }
1.33 + }
1.34 +
1.35 + /**
1.36 + * A new amount.
1.37 + * @param amount the quantity of the currency; must not be null
1.38 + * @param currency the currency; must not be null
1.39 + */
1.40 + public MonetaryAmount( final double amount, final Currency currency ) {
1.41 + this( new BigDecimal( amount ), currency );
1.42 + }
1.43 +
1.44 + /**
1.45 + * The amount.
1.46 + * @return the amount
1.47 + */
1.48 + public BigDecimal getAmount() {
1.49 + return amount;
1.50 + }
1.51 +
1.52 + /**
1.53 + * The currency.
1.54 + * @return the currency
1.55 + */
1.56 + public Currency getCurrency() {
1.57 + return currency;
1.58 + }
1.59 +
1.60 + /**
1.61 + * The string representation of the monetary amount.
1.62 + * @return the amount, a non-breakable space, the currency
1.63 + */
1.64 + @Override
1.65 + public String toString() {
1.66 + return amount.toPlainString() + "\u00a0" + currency.toString();
1.67 + }
1.68 +
1.69 + /**
1.70 + * Two monetary amounts are equal to each other iff they have equal amounts of equal currencies.
1.71 + * @param other the other object
1.72 + * @return equality
1.73 + */
1.74 + @Override
1.75 + public boolean equals( final Object other ) {
1.76 + if ( other instanceof MonetaryAmount ) {
1.77 + final MonetaryAmount otherMonetaryAmount = (MonetaryAmount) other;
1.78 + return getAmount().equals( otherMonetaryAmount.getAmount() ) && getCurrency().equals( otherMonetaryAmount.getCurrency() );
1.79 + }
1.80 + return false;
1.81 + }
1.82 +
1.83 + /**
1.84 + * The hash code combines the hash codes of the amount and of the currency.
1.85 + * @return hash code
1.86 + */
1.87 + @Override
1.88 + public int hashCode() {
1.89 + return amount.hashCode() * 37 + currency.hashCode();
1.90 + }
1.91 +
1.92 +}