001package algs34; 002import stdlib.*; 003import java.util.HashSet; 004/* *********************************************************************** 005 * Floating point is a pain! 006 *************************************************************************/ 007 008public final class XBadPoint { 009 static class BadPoint { 010 private final double x; 011 private final double y; 012 public BadPoint(double x, double y) { this.x = x; this.y = y; } 013 public String toString() { return "(" + x + ", " + y + ")"; } 014 015 public boolean equals(Object other) { 016 if (other == this) return true; 017 if (other == null || other.getClass() != this.getClass()) return false; 018 BadPoint that = (BadPoint) other; 019 if (this.x != that.x) return false; 020 if (this.y != that.y) return false; 021 return true; 022 } 023 public int hashCode() { 024 int h = 17; 025 h = 31*h + Double.hashCode(x); 026 h = 31*h + Double.hashCode(y); 027 return h; 028 } 029 } 030 031 public static void main(String[] args) { 032 BadPoint a = new BadPoint(0.0, 0.0); 033 BadPoint b = new BadPoint(0.0, 0.0); 034 BadPoint e = new BadPoint(0.0,-0.0); 035 StdOut.format("a = %s [hashcode=%d]\n", a, a.hashCode ()); 036 StdOut.format("b = %s [hashcode=%d]\n", b, b.hashCode ()); 037 StdOut.format("e = %s [hashcode=%d]\n", e, e.hashCode ()); 038 039 HashSet<BadPoint> set = new HashSet<>(); 040 set.add(a); 041 StdOut.println("Added a"); 042 StdOut.println("a == b: " + (a == b)); 043 StdOut.println("a.equals(b): " + (a.equals(b))); 044 StdOut.println("contains b: " + set.contains(b)); 045 StdOut.println("a == e: " + (a == e)); 046 StdOut.println("a.equals(e): " + (a.equals(e))); 047 StdOut.println("contains e: " + set.contains(e)); 048 } 049}