Skip to content

Currency should implement Comparable<Currency> #38

@EJP286CRSKW

Description

@EJP286CRSKW

It kind of does internally, but with a lot of extra mucking around. Proposed solution follows.

public class Currency
        // Added EJP 31/8/2023
        implements Comparable<Currency> {
	Long embeddedValue = null;

	/**
	 * constructor that takes a long already in COM representation
	 * 
	 * @param newValue New value.
	 */
	public Currency(long newValue) {
		embeddedValue = new Long(newValue);
	}

	/**
	 * constructor that takes a String already in COM representation
	 * 
	 * @param newValue New value.
	 */
	public Currency(String newValue) {
		embeddedValue = new Long(newValue);
	}

	/**
	 * Return the currency as a primitive long.
     * 
	 * @return the currency as a primitive long
	 */
	public long longValue() {
		return embeddedValue.longValue();
	}

	/**
	 * Getter to the inner Long so that {@link Comparable#compareTo} can work
	 * 
	 * @return the embedded Long value
	 */
	protected Long getLongValue() {
		return embeddedValue;
	}

	/**
	 * Compares the values of two currencies
	 * 
	 * @param anotherCurrency Currency object to compare to.
	 * @return the usual compareTo results
	 */
    @Override
	public int compareTo(Currency anotherCurrency) {
		return embeddedValue.compareTo(anotherCurrency.getLongValue());
	}

//	/**
//	 * standard comparison
//	 * 
//	 * @param o
//	 *            must be Currency or Long
//	 * @return the usual compareTo results
//   * Deleted EJP 31/8/2023 when I added 'implements Comparable<Currency>.
//   * The compiler will still generate this method as a bridge method. 
//	 */
//	public int compareTo(Object o) {
//		if (o instanceof Currency) {
//			return compareTo((Currency) o);
//		} else if (o instanceof Long) {
//			return embeddedValue.compareTo((Long) o);
//		} else
//			throw new IllegalArgumentException(
//					"Can only compare to Long and Currency not "
//							+ o.getClass().getName());
//	}

	/*
	 * {@inheritDoc}
	 */
    @Override
	public boolean equals(Object o) {
		if (o == null) {
			return false;
        // Modified EJP 31/8/2023
		} else if (o instanceof Currency && compareTo((Currency)o) == 0) {
			return true;
		} else {
			return false;
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions