001package algs31; 002import stdlib.*; 003/* *********************************************************************** 004 * Compilation: javac Person.java 005 * Execution: java Person 006 * 007 * Implementing equals() in a client-defined type. 008 * 009 *************************************************************************/ 010 011public final class XPerson { 012 private final String name; 013 private final long info; 014 015 public XPerson(String name, long info) { 016 this.name = name; 017 this.info = info; 018 } 019 020 // how you're supposed to implement equals 021 public boolean equals(Object y) { 022 if (y == this) return true; 023 if (y == null) return false; 024 if (y.getClass() != this.getClass()) return false; 025 XPerson that = (XPerson) y; 026 return (this.name.equals(that.name)) && (this.info == that.info); 027 } 028 029 public String toString() { 030 return name + " " + info; 031 } 032 033 public static void main(String[] args) { 034 XPerson a = new XPerson("Alice", 1234); 035 XPerson b = new XPerson("Alice", 1234); 036 XPerson c = new XPerson("Bob", 1234); 037 XPerson d = new XPerson("Alice", 4321); 038 StdOut.println("a = " + a); 039 StdOut.println("b = " + b); 040 StdOut.println("c = " + c); 041 StdOut.println("d = " + d); 042 StdOut.println("a == a: " + a.equals(a)); 043 StdOut.println("a == b: " + a.equals(b)); 044 StdOut.println("a == c: " + a.equals(c)); 045 StdOut.println("a == d: " + a.equals(d)); 046 } 047 048 049 050}