Last active
May 13, 2019 03:42
-
-
Save khoatran/ed208ec8147f16edc0ef5ce92143e6b9 to your computer and use it in GitHub Desktop.
Liskov - violation - hashCode example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* From Effective Java book - 2nd Edition - Author: Joshua Bloch | |
*/ | |
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>(); | |
m.put(new PhoneNumber(707, 867, 5309), "Jenny"); | |
String result = m.get(new PhoneNumber(707, 867, 5309)) // result = ?? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment