001package algs31;
002import stdlib.*;
003import java.util.HashSet;
004/* ***********************************************************************
005 *  Compilation:  javac PhoneNumber.java
006 *  Execution:    java PhoneNumber
007 *  Dependencies:
008 *
009 *  Immutable data type for US phone numbers.
010 *
011 *************************************************************************/
012
013public final class XPhoneNumber {
014        private final int area;   // area code (3 digits)
015        private final int exch;   // exchange  (3 digits)
016        private final int ext;    // extension (4 digits)
017
018        public XPhoneNumber(int area, int exch, int ext) {
019                this.area = area;
020                this.exch = exch;
021                this.ext  = ext;
022        }
023
024        // how you're supposed to implement equals
025        public boolean equals(Object y) {
026                if (y == this) return true;
027                if (y == null) return false;
028                if (y.getClass() != this.getClass()) return false;
029                XPhoneNumber that = (XPhoneNumber) y;
030                return (this.area == that.area) && (this.exch == that.exch) && (this.ext == that.ext);
031        }
032
033        // 0 for padding with leading 0s
034        public String toString() {
035                return String.format("(%03d) %03d-%04d", area, exch, ext);
036        }
037
038        // satisfies the hashCode contract
039        public int hashCode() {
040                return 31 * (area + 31 * exch) + ext;
041        }
042
043
044        public static void main(String[] args) {
045                XPhoneNumber a = new XPhoneNumber(609, 258, 4455);
046                XPhoneNumber b = new XPhoneNumber(609, 876, 5309);
047                XPhoneNumber c = new XPhoneNumber(609, 003, 5309);
048                XPhoneNumber d = new XPhoneNumber(215, 876, 5309);
049                XPhoneNumber e = new XPhoneNumber(609, 876, 5309);
050                StdOut.println("a = " + a);
051                StdOut.println("b = " + b);
052                StdOut.println("c = " + c);
053                StdOut.println("d = " + d);
054                StdOut.println("e = " + e);
055
056                HashSet<XPhoneNumber> set = new HashSet<>();
057                set.add(a);
058                set.add(b);
059                set.add(c);
060                StdOut.println("Added a, b, and c");
061                StdOut.println("contains a:  " + set.contains(a));
062                StdOut.println("contains b:  " + set.contains(b));
063                StdOut.println("contains c:  " + set.contains(c));
064                StdOut.println("contains d:  " + set.contains(d));
065                StdOut.println("contains e:  " + set.contains(e));
066                StdOut.println("b == e:      " + (b == e));
067                StdOut.println("b.equals(e): " + (b.equals(e)));
068        }
069
070
071
072}