package class9_1_GeneratingHashCodes_021; // Josiah Yoder, MSOE, 04 May 2015 import java.util.HashMap; public class Complex { private int real; private int imag; public Complex(int real, int imag) { this.real = real; this.imag = imag; } /** * Indicates whether some other object is "equal to" this one. *

* The {@code equals} method implements an equivalence relation * on non-null object references: *

*

* The {@code equals} method for class {@code Object} implements * the most discriminating possible equivalence relation on objects; * that is, for any non-null reference values {@code x} and * {@code y}, this method returns {@code true} if and only * if {@code x} and {@code y} refer to the same object * ({@code x == y} has the value {@code true}). *

* 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 {@code true} if this object is the same as the obj * argument; {@code false} otherwise. * @see #hashCode() * @see HashMap */ @Override public boolean equals(Object obj) { // TODO: consider false if error... 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: *

*

* As much as is reasonably practical, the hashCode method defined by * class {@code Object} does return distinct integers for distinct * objects. (This is typically implemented by converting the internal * address of the object into an integer, but this implementation * technique is not required by the * Java™ programming language.) * * @return a hash code value for this object. * @see Object#equals(Object) * @see System#identityHashCode */ @Override public int hashCode() { return 2*this.real + this.imag; } }