package class9_2_GeneratingHashCodes_051; // Josiah Yoder, MSOE, 04 May 2015 import java.util.HashMap; public class Complex { private int real; private int imag; private String name = "Bob"; public Complex(int real, int imag) { this.real = real; this.imag = imag; } /** * Indicates whether some other object is "equal to" this one. * ... * Note that it is generally necessary to override the {@code hashCode} * method whenever this method is overridden, so as to maintain the * general contract for the {@code hashCode} method, which states * that equal objects must have equal hash codes. * * @param obj the reference object with which to compare. * @return true if both real and imaginary parts match. * @see #hashCode() * @see HashMap */ @Override public boolean equals(Object obj) { if(!(obj instanceof Complex)) { return false; } else { Complex c = (Complex) obj; return this.real == c.real && this.imag == c.imag; } } /** * Returns a hash code value for the object. This method is * supported for the benefit of hash tables such as those provided by * {@link HashMap}. *

* The general contract of {@code hashCode} is: *

*

* * @return a hash code value for this object. * @see System#identityHashCode */ @Override public int hashCode() { return 31*this.real + 19*this.imag + 23*this.name.hashCode(); } }