japod@6: package org.apidesign.apifest08.currency; japod@6: japod@6: import java.math.BigDecimal; japod@6: import java.util.Currency; japod@6: japod@6: /** japod@6: * An amount of a currency. japod@6: * Immutable. japod@6: * @author jdvorak japod@6: */ japod@6: public class MonetaryAmount { japod@6: japod@6: private final BigDecimal amount; japod@6: private final Currency currency; japod@6: japod@6: /** japod@6: * A new amount. japod@6: * @param amount the quantity of the currency; must not be null japod@6: * @param currency the currency; must not be null japod@6: */ japod@6: public MonetaryAmount( final BigDecimal amount, final Currency currency ) { japod@6: this.amount = amount; japod@6: this.currency = currency; japod@6: if ( amount == null ) { japod@6: throw new NullPointerException( "The amount" ); japod@6: } japod@6: if ( currency == null ) { japod@6: throw new NullPointerException( "The currency" ); japod@6: } japod@6: } japod@6: japod@6: /** japod@6: * A new amount. japod@6: * @param amount the quantity of the currency; must not be null japod@6: * @param currency the currency; must not be null japod@6: */ japod@6: public MonetaryAmount( final double amount, final Currency currency ) { japod@6: this( new BigDecimal( amount ), currency ); japod@6: } japod@6: japod@6: /** japod@6: * The amount. japod@6: * @return the amount japod@6: */ japod@6: public BigDecimal getAmount() { japod@6: return amount; japod@6: } japod@6: japod@6: /** japod@6: * The currency. japod@6: * @return the currency japod@6: */ japod@6: public Currency getCurrency() { japod@6: return currency; japod@6: } japod@6: japod@6: /** japod@6: * The string representation of the monetary amount. japod@6: * @return the amount, a non-breakable space, the currency japod@6: */ japod@6: @Override japod@6: public String toString() { japod@6: return amount.toPlainString() + "\u00a0" + currency.toString(); japod@6: } japod@6: japod@6: /** japod@6: * Two monetary amounts are equal to each other iff they have equal amounts of equal currencies. japod@6: * @param other the other object japod@6: * @return equality japod@6: */ japod@6: @Override japod@6: public boolean equals( final Object other ) { japod@6: if ( other instanceof MonetaryAmount ) { japod@6: final MonetaryAmount otherMonetaryAmount = (MonetaryAmount) other; japod@6: return getAmount().equals( otherMonetaryAmount.getAmount() ) && getCurrency().equals( otherMonetaryAmount.getCurrency() ); japod@6: } japod@6: return false; japod@6: } japod@6: japod@6: /** japod@6: * The hash code combines the hash codes of the amount and of the currency. japod@6: * @return hash code japod@6: */ japod@6: @Override japod@6: public int hashCode() { japod@6: return amount.hashCode() * 37 + currency.hashCode(); japod@6: } japod@6: japod@6: }