File tree Expand file tree Collapse file tree 1 file changed +39
-1
lines changed
Expand file tree Collapse file tree 1 file changed +39
-1
lines changed Original file line number Diff line number Diff line change @@ -900,4 +900,42 @@ public boolean equals(Object o) {
900900
901901- 如果两个对象根据 equals(Object) 方法比较是不相等的,那么调用两个对象中任意一个对象的 hashCode 方法,则不一定要产生不同的整数结果。但是作为程序员应该知道,给不相等的对象产生截然不同的整数结果,有可能提高散列表(hashTable)的性能。
902902
903- ** 因没有覆盖 hashCode 而违反的关键约定是第二条:相等的对象必须具有相等的散列码(hash code)** 。根据类的 equals 方法,两个截然不同的实例在逻辑上是有可能相等的,但是,根据 Object 类的 hashCode 方法,它们仅仅是两个没有共同之处的对象。因此,对象的 hashCode 方法返回两个看起来是随机的整数,而不是根据第二个约定所要求的那样,返回两个相等的整数。
903+ ** 因没有覆盖 hashCode 而违反的关键约定是第二条:相等的对象必须具有相等的散列码(hash code)** 。根据类的 equals 方法,两个截然不同的实例在逻辑上是有可能相等的,但是,根据 Object 类的 hashCode 方法,它们仅仅是两个没有共同之处的对象。因此,对象的 hashCode 方法返回两个看起来是随机的整数,而不是根据第二个约定所要求的那样,返回两个相等的整数。
904+
905+ 上 demo,看下面的 PhoneNumber 类,它的 equals 方法是根据第 8 条中给出的“诀窍”构造出来的:
906+
907+ ``` java
908+
909+ public final class PhoneNumber {
910+ private final short areaCode;
911+ private final short prefix;
912+ private final short lineNumber;
913+
914+ public PhoneNumber (short areaCode , short prefix , short lineNumber ) {
915+ this . areaCode = areaCode;
916+ this . prefix = prefix;
917+ this . lineNumber = lineNumber;
918+ }
919+
920+ @Override
921+ public boolean equals (Object o ) {
922+ if (o == this ) {
923+ return true ;
924+ }
925+
926+ if (! (o instanceof PhoneNumber )) {
927+ return false ;
928+ }
929+
930+ PhoneNumber pn = (PhoneNumber )o;
931+
932+ return pn. areaCode = this . areaCode && pn. prefix = this . prefix
933+ && pn. lineNumber = this . lineNumber;
934+ }
935+
936+ // Broken -- no hashCode method
937+
938+ ... // Remainder omitted
939+ }
940+
941+ ```
You can’t perform that action at this time.
0 commit comments