$ L9 Y o4 s, ^) ~* f( VObject 类是 Java 中所有类的超类,在 Java 中每个类都是由它扩展来的,只有基本类型(primitive types)不是对象,剩下的引用类型都是对象,包括对象数组或者基本类型数组。- _6 T% f7 F$ U$ b. \7 U
* Z8 N% Y2 g. G9 mObject obj = new int[10] // ok 1 x4 l. P- O4 F* U$ g. G10 c0 B7 b. T7 F( z* w
Object 方法概览: + M# y' B* \' ?4 `& Q2 X & e- W7 k" o% ?3 G0 {: Rpublic final native Class<?> getClass(); ; b& U! L5 Z% ^/ K2 x' Tpublic native int hashCode(); ) L* J+ J1 ^5 U+ P8 Upublic boolean equals(Object obj) {} . q3 Z6 a$ [0 }8 @( Sprotected native Object clone() throws CloneNotSupportedException;; R$ K' j' g3 n0 q* b3 k6 A
public String toString() {} ( R6 p0 X- d, W2 tpublic final native void notify(); , ?! F) N' \- x ^7 w2 bpublic final native void notifyAll(); ) j- [; f+ ?7 Z, ]9 e( spublic final native void wait(long timeout) throws InterruptedException;3 ^0 q0 W* ~9 y
public final void wait(long timeout, int nanos) throws InterruptedException{}' H R V* H% X5 n
public final void wait() throws InterruptedException {}0 U) Q% }1 R- r) x8 E$ k' b" b
protected void finalize() throws Throwable {} // Deprecated + J1 ^9 ]( R5 T1 ; q* N3 k6 q( ~4 q) s25 H+ S/ \9 `$ d5 {0 [5 N, B1 E* W
3 1 B( A/ K* }% R8 [7 H2 y$ B5 X49 [1 d; J: f$ J* y+ V
5* m* P. k. V7 Q1 v% x! i. R
6 % a/ k. i1 a2 M3 n# D7; ^5 z& O {0 C: p& b
8( x! J: Z% \ |
9 2 |' ` q# T& S. ]) h9 O3 H10; s6 b0 K l3 \ k) P, z
11) n% k3 B2 {8 Y, S
equals 方法 1 J6 E% B F) I' i$ J% O1 P2 N9 E4 }8 s) f6 U" L
public boolean equals(Object obj) { & M/ z* Q |% U$ u3 u return (this == obj);( P3 i; {; m/ k# |: V3 S
}! g n3 }: {5 t8 v
15 M# [) @7 |4 d* T; p9 A
21 ~( @- r5 Z2 k& q' n1 T
3 : Z" d! B n8 Y, x4 u/ C7 {/ m4 s阅读源码可知,Object 中的 equals 方法是比较两个对象是否有相同的引用,但是这在有些情况下是没有意义的,更多的时候是想比较两个对象的状态是否相同。 2 v! ~ I& F% {' }0 D; k3 |" R) p, j/ J- y8 b2 e
The equals method implements an equivalence relation on non-null object references:: M; Y" F( d' M; v( h
It is reflexive: for any non-null reference value x, x.equals(x) should return true.+ ~8 g4 @) `4 Y% c+ q8 H
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. 8 m7 X1 U {) h1 bIt is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. $ _( k, C. `* S5 s( ]It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. A7 |( C7 e7 B" ~For any non-null reference value x, x.equals(null) should return false.[2] ; Q6 N& `, j3 e3 S由 JDK 文档中可知,实现了 non-null 对象引用的相等关系的 equals 方法有五个特性:reflexive(自反性),symmetric(对称性),transitive(传递性),consistent(一致性),与 null 相比返回 false9 `, W' I a! E% q
1 \7 |# t* W x+ H) K
public class Person {2 C4 P9 V( S( g+ h- \. j0 m
private String name;$ K4 I5 F* Y! j" D
private int age; 8 Y, |, f8 R* p' c: o& ^! I% g, {, {+ N+ R2 J& @
@Override2 N" w& \$ N! a. h# F6 G
public boolean equals(Object o) {3 [4 a' Q" D( g# s. K0 `: `
// a quick test to see if the objects are identical : x, s+ x9 R0 y2 O8 B' O if (this == o) return true;+ l2 g& R7 E2 {* V! R
// if o == null or the classes don't match, they can't be equal4 P$ K5 g' q5 k' ?3 s+ J: `
if (o == null || getClass() != o.getClass()) return false;2 P! E( U& `2 x' P
, `) T* g" |7 ^
// now we know o is a non-null Person+ }+ O. w) [" [& y
Person person = (Person) o;& a9 \3 g2 y( ^% F4 `
& l2 d2 \. j) ~$ R0 \7 f8 i! U3 l& ] // test whether the fields have identical values 9 e9 z* P9 P9 Q# L A if (age != person.age) return false;' B' i' V" b% G7 a2 `1 I0 m
return Objects.equals(name, person.name);8 e# }" l/ n% C+ v# Y( i$ x
} 4 ~2 z! {" D* Z% I& t% q} , t+ \2 u7 o/ a9 L" j7 c8 A1 3 A8 n* o$ p9 |! n" k22 x( l. V- { M4 S
3. j5 V1 V6 w7 G/ |7 u# ~+ v% Z6 p
42 w- H9 q( ^3 ?2 D( K' ?
5% t$ X8 a" l7 E. W1 R9 G
6 * f% ^3 J3 y& G, C) j7 ( E; l8 H' {5 `: ]! _8 ( b& x0 C* @9 Q, J6 M: ?9 7 ?6 \. |; i b3 X107 E7 ]! Z1 }# O
11 ) N6 T, x; w# j' x7 V12 / B# F8 ]9 f& `& W6 D13 0 v- a6 L: l @, j2 b$ \14' P) R" i6 f; m+ R* ?' X. e
15 & ^% X& Y& c4 R16) u2 e1 j7 i' }) q
178 D7 D7 d9 e8 j5 ]7 \
18 $ V) Q0 C2 M+ t! O+ f: s198 [2 {0 S* N1 w# U# k
注意,比较可能为空的变量时可以使用Objects.equals() + P, z( x; B) L: f$ R; Z; f# u7 K! m$ R* L+ [% A
子类的 equals 方法:9 l' h/ {* S) c. z
# {1 R4 X4 d S) Q7 T) a2 \) w; cpublic class Student extends Person { 8 p' F- }. ` l4 e) P0 r private String school; , Y. f0 E# ? l- M' P; C5 t; u, k9 ]% P. ]8 F
@Override 4 \! B# A. S/ v0 o, ^ public boolean equals(Object o) { . k8 x6 `5 W* W/ Y/ T if (!super.equals(o)) return false;$ f7 U( y9 V; Q) P! ~% s7 c& w( b& {1 P
7 ~; q: ~; Z+ |0 j} 5 [+ H/ S# q- d9 H; ]14 P9 v' e+ I* d( c# ^. |) H8 \
2 9 A W2 z; b! f% a1 G" @1 G3, f: ~# A5 r; k9 [
4; I! M4 g0 `% Y( b8 v$ R
5 : b+ E; g* g+ m0 `5 [& W6 ' }8 S9 S1 ? L- A0 l# \0 ^, x/ h77 d; w& h! [# m% j
8 ! \" l4 {. N& K- f' t98 p- ^. o2 X& k! S' t. r: h
10* t( n* U7 Q2 t/ r6 g" A" T2 }" c
11 8 [ L) V9 O. t123 x i: j- W" m5 m
13 3 M, B H; F% L2 {) x3 G' u14$ d; x; h2 ~, O, y! a1 z
153 B' b! o- Q# k5 c9 m J! j j
16 ' S( o1 R3 v) W- g5 }$ [177 f3 H; t) @8 n: }: U" J5 c
189 w% r# S: b8 n* |2 O s
19 5 z j0 ?1 U7 W20 7 w& m4 u0 V4 u. d+ _0 {21 + X7 N; L( \$ {! P3 X7 m+ u. \5 b* K22 3 _ w0 I1 E' f5 T/ p+ B- e23# m* Y* N7 l3 }8 g1 N9 g8 F0 h( q. v
观察上述代码我们可以发现,getClass所返回的值与对象变量此刻的对象引用有关。. p0 D7 r; i, z2 J; y
- G7 ?+ e; A7 `& ?" o相等测试与继承 6 ~0 V5 O: J$ C3 Q/ k! d$ w, u; H' G3 G. \* i- E1 U( g& W( z
我们来看,如果复习的 equals 方法中使用 instanceof 来进行相等判断,即使用以下代码片段 1 ?) X0 B9 {* t9 m- @6 u # o1 h& n$ L) j _$ |class Father { 1 \& G+ p% B( e8 W2 g) ]- j private String name; * I) s; M" G. R- L' i5 }9 k; A8 X( q8 G
@Override+ t+ _; c, Q4 D v& f$ ~
public boolean equals(Object o) {0 @ ^; Q/ a1 s& K
if (this == o) return true;" L' Z! _8 L' @( b S
if (o == null || o instanceof Father) return false; " r( t4 [: C5 _- k, C, T Father father = (Father) o; 8 I$ v3 N% r3 H/ F0 h& w; e: y return Objects.equals(name, father.name);- t. Q% \) y8 }2 h* S
} ; \& c/ Q6 l. p} 4 B% J2 {6 L; r" y* }) |: `0 e! q; i. _8 m: C' f. ]
class Son extends Father implements MyInterface{9 ?6 c; W- {8 y9 k; G
private int age; * v% O2 D- Q) [3 C( U# f: d( \6 H! r2 M% v% E& {
@Override$ [( A( J9 A. `: X& t$ t1 |
public boolean equals(Object o) { ; P& K0 Y* R9 y if (this == o) return true;" F! f1 L" h$ _: ~; a! Q
if (o == null || o instanceof Son) return false; // not good8 p" ?% U: |+ B0 v( j
if (!super.equals(o)) return false;6 p& }3 R, i9 D, [' b' Z
Son son = (Son) o;6 W, X0 A9 C2 C0 n/ n
return age == son.age;5 W8 x( G. r6 R/ M) Q
}' }7 z8 Y- O+ @* ]& Q
} , x2 Z R# O6 h8 @18 m7 n# t; [7 |, \, X& b6 J$ J
2' q& H+ |* e c" d2 j
36 M/ J/ e4 T# r, \+ z: \8 b
4 , v! ]; o, ]6 p% j' C% V6 y58 |6 t* i2 `0 j. Q4 ^: N Y
6* {/ j/ k- S8 Q' N9 R
7 0 S' @# H P9 E" Y8 M6 ]) C: G5 y
95 T `. h/ J1 t. r( p9 B
10 J- ]! A& N0 F) q- I8 @+ |, P11 4 V, P4 M" C) I8 ?# F* z4 a, p12 / M( s8 O/ Y0 {6 c* F13 . h6 Y& f* s$ _( c& @' ~0 K148 w( N6 h6 _9 E* z! [# G
157 W% A g/ V! m+ v$ B
16 * n( ~& ^+ s5 K9 w; f7 e171 h; r& ?% c+ S! \2 g! o4 Y
18 . ~; e+ U# J% b# @3 p( A2 g19 0 X5 d7 T4 Z8 |( m+ A20, D8 j# O5 R. G
21 9 t& x4 N$ ~1 @! j22 & V& n* T3 M8 _3 v- Y, j9 Z. m23" [% x& p" d6 h, \
244 F E4 D1 M7 `+ N; Q$ T
当运行 f.equals(s) 判断时(f 为 Father 对象, s 为 Son 对象,假设两个对象中 name 一致),根据代码会返回 true, 但是当运行s.equals(f) 会引用 instanceof 判断失败而返回 false, 这就不符合自反性。6 F: e' M! z2 w1 K
9 \2 A5 c/ u6 Z; G. G) S( [: y- U
综上,我们可以得出结论% y) H( X7 F2 Z% r4 X2 @# n
& e; ?* d9 I; F9 X如果子类有自己相等的概念,如 Son 对象还需要比较彼此 age 是否相等,则对程序需求将强制采用 getClass 进行相等性检测。( J P/ N- f1 G/ w# u
如果有超类绝对相等的概念,那么可以用 instanceof 进行检测,只需要超类提供 equals 方法,并且要标为 final, 子类全部继承超类的 equals 方法,这样不同子类之间也可以进行比较。 3 E2 ^; i0 k& O3 K* L3 z3 r复写 equals 方法的步骤: 1 F' N2 _& z3 S0 j0 k" p . O9 T7 j! R; t" b, _. y现实参数命名为 otherObject7 ]9 U7 [$ s0 b" b0 V9 X7 ?! R
检测 this 和otherObject 是否引用同一个对象: if (this == otherObject) return true;7 ?( @/ H e W, e9 z2 M7 F* |
检测 otherObject 是否为 null: if (otherObject == null) return false; . f' H& t% N% s9 q, x: }( Y6 _$ k2 a比较 otherObject 与 this 是否时同一类,如果 equals 语义在每个子类中有所改变,就使用 getClass 进行检测: if (getClass() != otherObject.getClass()) return false;如果所有的子类都有统一的语义,就使用 instanceof 检测: if (!(otherObject instanceof ClassName)) return false;# j! E& u. @% H
将 otherObject 转化为相应的类型变量:ClassName other = (ClassName) otherObject- q$ h. ^# X2 G6 Y
进行域的比较,如果是基本类型使用 ==, 如果是引用类型可以使用 Objects.equals(), 如果是 数组类型的域, 可以使用 Arrays.equals()进行比较。* P: o. ]% x/ H: s
hashCode 方法! Y G) Q2 |/ ~; h3 t
. E! ?5 _: G% c; O3 x( R; e
散列码(hash code)是由对象导出的一个整数值,散列码是没有规律的,不同的对象其散列码一般不同, 5 H' d0 b- G5 Q6 f$ v! u, J # M7 B {" }! AThe general contract of hashCode is: M% o: l, U+ v" }2 j$ A4 N% i% v
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. ) [* l& r0 Y* b r5 F* xIf two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result./ r0 ~9 c4 K$ T v' g( w3 n' {
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables. 5 l2 E. S/ |5 g U6 P. XAs much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)[2]+ y# t. H: u* N9 q9 J' I6 R' s
翻译: * K* W! e& H! W$ c; e在一个 Java 程序的执行中,无论何时,hashcode 返回的值都应该是同一个 2 R. q$ q5 ? N7 Q如果 a.equals(b) 为 true, 那么一定有 a.hashcode() == b.hashcode()3 q% v% U. p* Y
如果 a.equals(b) 为 false,那么 a.hashcode() 与b.hashcode()不一定不同 5 s8 _9 H0 R" d' _; v" t: \public native int hashCode();3 J/ _/ U) d4 |/ g3 d p" O
11 p. y; ], o6 K3 V" g
以上为 Object 中的 hashcode方法,我们可以看到这是用 native 修饰的方法,表明该方法是使用了 JNI(Java Native Interface),使用了 C 或 C++ 进行实现。在实际情况下,大部分不同对象会 生成不同的 hashcode(通过将内存地址转换为整数) : e6 _# D9 u3 ]% T" d; {0 n0 J0 b. j6 Q
The main objectives of native keyword are:[5] & b( S; A; m- q2 O5 `3 Y6 A4 E. q/ P$ l0 z- z0 B
To improve performance of the system.$ _6 L9 |# |( U, v
To achieve machine level/memory level communication. + D. I" F! @$ z! q# s. p7 BTo use already existing legacy non-java code. ! K5 X9 ^8 _! h$ [# e测试代码: 2 G3 R4 I. @5 V: D# K$ N0 X. U. g" J2 c. Z
ublic class HashCode {6 V1 E2 {' u J3 h0 ?' O3 }7 Z
8 Z' A$ g" h# ]/ W0 B
public static void main(String[] args) { ; \- P6 Z5 j# j1 V) S Map<Student, String> map = new HashMap<>();6 ~ T- z* r) ]1 ?
Student s = new Student("Alice", 11); ~7 b1 S0 S( S9 S9 t# Y# W/ O8 `$ g, }1 c$ W
map.put(s, "Alice");& J n7 a" b4 s
map.put(new Student("Bob", 12), "Bob"); # ^ d. ]9 u+ }1 z% a7 Q8 { map.put(new Student("Cici", 15), "Cici");' J! n4 a8 d* q
* j2 P: o1 v3 n! [. i1 E if (map.containsKey(s)) {2 Q% Q9 ^5 J, i' b& z6 }3 ^
System.out.println("bingo"); // bingo " N* ^$ T5 C; d' W) K6 t }/ B2 |* U- B) W V3 K
0 C) e. Z; P8 \! I& T/ K if (map.containsKey(new Student("Bob", 12))) { 5 J) _6 R- o4 N$ {8 i System.out.println("hello"); // hello g# a) z! ?1 E. F; y
}3 C+ [# \( {+ Q% b4 x
} % ^! c- H7 A9 {4 ^ , j1 O3 Y& G6 b7 ^} + h( Z6 @7 z3 J# U) M4 B5 \6 G0 T% Q" a/ f: v
class Student {. Z h8 w: Y. Q+ I$ m: L2 Y' N2 I& ?* v" y
private String name; $ \$ q! b+ [ w" b. O; c private int age;6 p: I& u9 G2 @
3 V0 l2 C9 i" i$ E0 x' T* S
public Student(String name, int age) { 4 B$ P+ w0 |; X! b+ H# E this.name = name; H$ T3 t: i* `* L: P this.age = age;& V s: W( Y+ M( t% }* l* ?9 X
}6 K+ A; h8 g2 B h
! b x+ k5 Z! y/ v" J9 n- a6 u @Override8 K+ C) Z1 {# z4 H
public boolean equals(Object o) {& z: y& s) w( U3 [1 a
if (this == o) return true; 4 ]* e8 c6 r$ G" w4 ]/ r if (o == null || getClass() != o.getClass()) return false;$ m) b$ W" _( _! b' S6 v) L
Student student = (Student) o; , a/ ~; H1 ~! c3 j+ E# u return age == student.age && 4 [# a. K l) B [) K Objects.equals(name, student.name);5 \1 I# i$ B8 l; a# [0 y% P
}+ }+ Q! a( U9 ]0 k# ^/ Z8 {
+ c4 n: @# g4 Q1 _$ a
@Override . P& _9 W* w% o n. I% c public int hashCode() {) J7 _& [. q* i
return Objects.hash(name, age); E2 t' s C K, p/ s2 Y5 f. C
} ) u8 z/ |8 j& I/ |. h1 p! N! g1 e7 W} , }% @' W H) B7 N1! i. b3 W3 w k2 _( o7 {! \
2 4 Z; m; e% k3 L) d6 @33 `* b" o: q! j/ r& g3 w
4 * I2 |& S1 l: u( H3 o5 / ~; z1 u/ J. c- R; r+ M67 T v9 B2 q% C! s! [5 f, f
7 : t# t4 j% |. ], _: Z82 }3 A) L1 G! `! b" R
9 7 S0 }1 P% @2 e3 ~! u9 h( H9 k10% T. B8 W; Q% Q& S8 M8 p" @
11 # u! A& B; w2 o* _+ {12 N! N& M4 ?4 v; l$ P6 x% o- ?
133 A& G% ~' l9 K9 s- X# h
142 Z9 k( p* N2 [& v* _. K
15 3 C5 O* x! f" d3 h160 G8 O" Q9 V/ g3 o$ _8 I% b
17( n6 E4 J! ?/ ?2 u0 W
183 E6 j0 K- C& w
19$ \5 a9 \ @% |3 X8 |! i. {3 v8 M/ L
20 9 g0 K& \" P) j4 J* K21 ) W% Q* V8 B* q22 6 b) E' k* c* i! i. ]23 E7 R, v! y+ e5 ^" l# K241 V7 e: K" C% {
25 , q+ ?2 o* v, _; Y0 A8 D' T26 ! a, @2 H) ^! e D! `+ {% ~: n7 f% ^27/ {+ N9 S Q7 E6 s1 d, W, Q
28 - `# C3 e* x6 _- H! `" H! P( m294 \0 T, }# h* G
30 " a( \+ V) I! h/ m7 R* O6 G. h31. F8 W+ D- f- b
32 & q/ S5 Y+ }4 `! p# }1 J( k33 3 J2 _: T1 b, X! o3 ]7 _34 5 _7 F- D/ U: @: p4 Z355 b) n$ a0 t1 D( ]" Z. Z
36 ( f( q# P- A. @; O* Q37 . l) ]& f1 R# R* l8 A0 b38 $ s- H ^$ O: z& O- o& P4 F39 # ?5 \0 Z& m) v6 U. u406 P0 T) A' d7 U& l* D' e& a/ A
414 W4 _- R" d$ s
429 l$ n: V7 e* \; S' V p
432 Y4 [4 N, I0 a( ~* C
44 9 Z+ A# D9 g' r6 b上述代码测试了,必须重写 equals 和 hashcode 方法,才能正常作为 map 的 key,如果有其中一个方法没有重写,都会造成 “hello” 不打印。 ) T( S( i8 I$ b$ J: o! s, a4 {1 D: G0 D: B- X: z
clone 方法 " O4 f- S% D, G; i! I& @$ a8 L $ L- [5 R4 A; T% v" c! _7 Dprotected native Object clone() throws CloneNotSupportedException; ( H V! b1 g* ]$ D0 Y1% ?; n; v% P& w: @: u
观察源码可知,clone 方法是 protected,子类只能调用受保护的 clone 方法来克隆它自己的对象,即只有在 Person 类中才可以克隆 Person 对象 / L& |( r( I" Z! L # ~4 }* ~; B! |, P& Z9 j2 e! Q( Epublic class CloneTest { ; h+ n: X- d9 k/ K public static void main(String[] args) {8 w7 |3 v! W% E. J" @; V& f
Person p = new Person(); , ?; }& g+ X S# J, Y Person p2 = p.clone(); // Error clone() has protected access in Object1 d3 Q* v: f+ h# \2 T7 K
}; r) n, _* t# }. l8 \- {
} Q" j3 M: I, s+ r( d% j9 w& |8 j* @9 I ?; `& P) O
class Person {! _, E2 f0 b; J
private String name; " ?1 P5 j' r* Q private int age; ' ^$ P/ d; w0 X. s" W} / C- O( g* [* V1 Z v1! N- N# _# j; z, I/ B4 Q' j
2 0 B/ ^! m( o- l6 l, f3 $ b4 W; a% W4 W& Y# M: P4" j% Z6 J" q, K( w! z# j+ y4 V3 s
5 ; F0 ?9 h$ v6 L# N9 [7 W6 8 s6 q( U6 J9 Q4 }, h. E9 x7 R: |7: j0 T$ G" T# ~
8 2 G$ s# p* ]8 I1 a8 o5 G/ {9 7 N& H0 [! i. h5 v- k8 T10 * w0 P n$ i0 K; p. u% i; z. b9 }11 # w. M) A9 c4 B! @. a: x我们可以重写 Person 中的 clone()方法为 public 即可调用1 H2 S' @6 `( B# b' }1 o
" R. X6 P) W0 k1 q, jpublic class CloneTest {. _; u1 @) U4 H
public static void main(String[] args) {3 f) s( w( F3 T# k0 Q2 x k3 g
Person p = new Person(); 0 d* W# x2 s; t5 } try {" P9 Y% t7 y$ s% F
Person p2 = p.clone();4 T& @2 J+ V- Y6 J$ h5 _7 f1 g
} catch (CloneNotSupportedException e) { , M& m$ q7 ~: v. }: V' N# c; F e.printStackTrace();1 i3 p1 `) m! A. X$ J
} a$ Y1 O8 r! J. e$ U
} |' D' W& G4 T% _9 d0 j}- X! N% l6 r% P) f3 n \$ w