mirror of
https://github.com/sjsdfg/effective-java-3rd-chinese.git
synced 2025-04-11 20:10:42 +08:00
update 11. 重写 equals 方法时同时也要重写 hashcode 方法
This commit is contained in:
parent
f2e2a16d79
commit
d4acbf6209
@ -12,7 +12,6 @@
|
||||
|
||||
```java
|
||||
Map<PhoneNumber, String> m = new HashMap<>();
|
||||
|
||||
m.put(new PhoneNumber(707, 867, 5309), "Jenny");
|
||||
```
|
||||
|
||||
@ -23,7 +22,6 @@ m.put(new PhoneNumber(707, 867, 5309), "Jenny");
|
||||
|
||||
```java
|
||||
// The worst possible legal hashCode implementation - never use!
|
||||
|
||||
@Override public int hashCode() { return 42; }
|
||||
```
|
||||
|
||||
@ -53,18 +51,12 @@ m.put(new PhoneNumber(707, 867, 5309), "Jenny");
|
||||
|
||||
```java
|
||||
// Typical hashCode method
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
|
||||
int result = Short.hashCode(areaCode);
|
||||
|
||||
result = 31 * result + Short.hashCode(prefix);
|
||||
|
||||
result = 31 * result + Short.hashCode(lineNum);
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
@ -77,12 +69,9 @@ public int hashCode() {
|
||||
|
||||
```java
|
||||
// One-line hashCode method - mediocre performance
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
|
||||
return Objects.hash(lineNum, prefix, areaCode);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
@ -90,28 +79,18 @@ public int hashCode() {
|
||||
|
||||
```java
|
||||
// hashCode method with lazily initialized cached hash code
|
||||
|
||||
private int hashCode; // Automatically initialized to 0
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
|
||||
int result = hashCode;
|
||||
|
||||
if (result == 0) {
|
||||
|
||||
result = Short.hashCode(areaCode);
|
||||
|
||||
result = 31 * result + Short.hashCode(prefix);
|
||||
|
||||
result = 31 * result + Short.hashCode(lineNum);
|
||||
|
||||
hashCode = result;
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
@ -125,4 +104,4 @@ public int hashCode() {
|
||||
|
||||
|
||||
|
||||
[1]: http://com.google.common.hash.hashing/
|
||||
[1]: http://com.google.common.hash.hashing/
|
||||
|
Loading…
Reference in New Issue
Block a user