package cse1030; /** * A simple phone number class that illustrates argument validation, constructor * chaining, equals, hashCode, and Comparable * * @author CSE1030 * */ public final class PhoneNumber implements Comparable { private final short areaCode; private final short exchangeCode; private final short stationCode; public PhoneNumber(int areaCode, int exchangeCode, int stationCode) { rangeCheck(areaCode, 999, "area code"); rangeCheck(exchangeCode, 999, "exchange code"); rangeCheck(stationCode, 9999, "station code"); this.areaCode = (short) areaCode; this.exchangeCode = (short) exchangeCode; this.stationCode = (short) stationCode; } public PhoneNumber(PhoneNumber n) { this(n.getAreaCode(), n.getExchangeCode(), n.getStationCode()); } private static void rangeCheck(int num, int max, String name) { if (num < 0 || num > max) { throw new IllegalArgumentException(name + " : " + num); } } public short getAreaCode() { return this.areaCode; } public short getExchangeCode() { return this.exchangeCode; } public short getStationCode() { return this.stationCode; } @Override public String toString() { return String.format("(%1$03d) %2$03d-%3$04d", this.areaCode, this.exchangeCode, this.stationCode); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + areaCode; result = prime * result + exchangeCode; result = prime * result + stationCode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PhoneNumber other = (PhoneNumber) obj; if (areaCode != other.areaCode) return false; if (exchangeCode != other.exchangeCode) return false; if (stationCode != other.stationCode) return false; return true; } @Override public int compareTo(PhoneNumber other) { int result = this.getAreaCode() - other.getAreaCode(); if (result == 0) { // area codes are the same; compare exchange codes result = this.getExchangeCode() - other.getExchangeCode(); if (result == 0) { // area and exchange codes are the same; compare station codes result = this.getStationCode() - other.getStationCode(); } } return 0; } public static void main(String[] args) { PhoneNumber cse = new PhoneNumber(416, 736, 5053); System.out.println(cse == cse); // true PhoneNumber cseToo = cse; System.out.println(cseToo == cse); // true PhoneNumber cseAlso = new PhoneNumber(416, 736, 5053); System.out.println(cseAlso == cse); } }