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