Some background on equality and hash code overrides in Java

Image for post
Image for post
Photo by Christopher Williams on Unsplash

Some very basic background information

    @Override
public int hashCode() {
return this.fieldA * this.fieldB;
}

Having the IDE write the overrides for you

Choosing the relevant fields

An example class: money amounts

package currency;import java.util.Currency;public class CurrencyAmount {    private final long units;
private final short cents;
private final Currency currencyID;
public CurrencyAmount(long singles, short cents,
Currency currency) {
this.units = singles;
this.cents = cents;
this.currencyID = currency;
}
}
package currency;import java.util.Currency;import static org.junit.Assert.*;public class CurrencyAmountTest {    private static final Currency DOLLARS =
Currency.getInstance("USD");
// private static final Currency YEN? EUROS? FRANCS? ETC.
}
    @Override
public String toString() {
return this.currencyID.getSymbol() + this.units + "."
+ this.cents;
}
    @Override
public String toString() {
return "Transaction " + this.amount.toString() + " on "
+ this.dateTime.toString();
}

Another example class: complex numbers

        private final double real;
private final double imag;
        ComplexNumber someNumber = new ComplexNumber(1.0, 1.0);
ComplexNumber sameNumber = new ComplexNumber(1.0, 1.0);
boolean flag = someNumber.equals(sameNumber);

In the next part

is a composer and photographer from Detroit, Michigan. He has been working on a Java program to display certain mathematical diagrams.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store