-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathPhoneNumber.java
More file actions
70 lines (62 loc) · 2.13 KB
/
PhoneNumber.java
File metadata and controls
70 lines (62 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Adding a toString method to PhoneNumber - page 44
package effectivejava.chapter3.item10;
import java.util.HashMap;
import java.util.Map;
public final class PhoneNumber {
private final short areaCode;
private final short prefix;
private final short lineNumber;
public PhoneNumber(int areaCode, int prefix, int lineNumber) {
rangeCheck(areaCode, 999, "area code");
rangeCheck(prefix, 999, "prefix");
rangeCheck(lineNumber, 9999, "line number");
this.areaCode = (short) areaCode;
this.prefix = (short) prefix;
this.lineNumber = (short) lineNumber;
}
private static void rangeCheck(int arg, int max, String name) {
if (arg < 0 || arg > max)
throw new IllegalArgumentException(name + ": " + arg);
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof PhoneNumber))
return false;
PhoneNumber pn = (PhoneNumber) o;
return pn.lineNumber == lineNumber && pn.prefix == prefix
&& pn.areaCode == areaCode;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + areaCode;
result = 31 * result + prefix;
result = 31 * result + lineNumber;
return result;
}
/**
* Returns the string representation of this phone number. The string
* consists of fourteen characters whose format is "(XXX) YYY-ZZZZ", where
* XXX is the area code, YYY is the prefix, and ZZZZ is the line number.
* (Each of the capital letters represents a single decimal digit.)
*
* If any of the three parts of this phone number is too small to fill up
* its field, the field is padded with leading zeros. For example, if the
* value of the line number is 123, the last four characters of the string
* representation will be "0123".
*
* Note that there is a single space separating the closing parenthesis
* after the area code from the first digit of the prefix.
*/
@Override
public String toString() {
return String.format("(%03d) %03d-%04d", areaCode, prefix, lineNumber);
}
public static void main(String[] args) {
Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>();
m.put(new PhoneNumber(707, 867, 5309), "Jenny");
System.out.println(m);
}
}