forked from itwanger/toBeBetterJavaer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava.md
More file actions
5707 lines (3984 loc) · 205 KB
/
Copy pathjava.md
File metadata and controls
5707 lines (3984 loc) · 205 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 二哥修订版《30天速通Java》
大家好,我是二哥呀。
GitHub 上有一个很知名的开源知识库《[CS-Notes](https://github.com/CyC2018/CS-Notes)》,目前已有 173k 的 star 数,其中收录了不少我认为蛮不错的内容,比如说大家现在看到的《30天速通Java》——请原谅我起了一个噱头十足的名字😁。
一共五个章节,基础篇、IO 篇、容器篇、并发篇和 JVM篇,我结合《[二哥的 Java 进阶之路](https://javabetter.cn/)》对内容做一些补充和优化,并导出了亮白版和暗黑版的 PDF 和 epub 版本,好方便大家在 30 天内真的速通 Java(减少大家学习的成本)。
- 由于时间仓促和个人能力有限,手册难免存在错误和疏漏,还请大家批评指正。微信 itwanger
- 该手册会持续更新,再次感谢原作者 CS-Notes,原文档地址:[https://github.com/CyC2018/CS-Notes/](https://github.com/CyC2018/CS-Notes/blob/master/notes/Java%20%E5%9F%BA%E7%A1%80.md)
- 推荐:[二哥的 Java 进阶之路:Java 最新学习路线](https://javabetter.cn/xuexiluxian/java/yitiaolong.html)
**最新版 PDF 获取**
讲个不好笑的笑话,PDF 内容没办法自动更新(😂),所以只能通过下面的方式:
> 微信搜索《**沉默王二**》或者微信扫下面的二维码,关注后回复《**java**》即可获取最新的 PDF 版本(我会不定期更新)。

获取方式见下图(我用的 PC 端微信截图,手机端差不多):

附其他干货笔记下载地址:
- [二哥的 Linux 速查备忘手册 PDF 下载](https://javabetter.cn/pdf/linux.html)
- [阮一峰 C 语言入门教程 PDF 下载](https://javabetter.cn/pdf/yuanyifeng-c-language.html)
- [Java 核心知识点整理 PDF 下载](https://javabetter.cn/pdf/github-java-jiaocheng-115-star.html)
- [深入浅出 Java 多线程 PDF 下载](https://javabetter.cn/pdf/java-concurrent.html)
- [Pro Git 中文版 PDF 下载](https://javabetter.cn/pdf/progit.html)
- [给操作系统捋条线 PDF 下载](https://javabetter.cn/pdf/os.html)
# 第一章、Java基础篇
## 一、数据类型
### 基本类型

Java 基本数据类型的默认值和占用大小:
| 数据类型 | 默认值 | 大小 |
| -------- | -------- | ------ |
| boolean | false | 1 字节或 4 字节 |
| char | '\u0000' | 2 字节 |
| byte | 0 | 1 字节 |
| short | 0 | 2 字节 |
| int | 0 | 4 字节 |
| long | 0L | 8 字节 |
| float | 0.0f | 4 字节 |
| double | 0.0 | 8 字节 |
推荐阅读:[二哥的 Java 进阶之路:Java 基本数据类型](https://javabetter.cn/basic-grammar/basic-data-type.html)
### 包装类型
基本类型都有对应的包装类型,基本类型与其对应的包装类型之间的赋值使用自动装箱与拆箱完成。
```java
Integer x = 2; // 装箱 调用了 Integer.valueOf(2)
int y = x; // 拆箱 调用了 X.intValue()
```
推荐阅读:[二哥的 Java 进阶之路:拆箱和装箱](https://javabetter.cn/basic-extra-meal/box.html)
### 缓存池
`new Integer(123)` 与 `Integer.valueOf(123)` 的区别在于:
- `new Integer(123)` 每次都会新建一个对象;
- `Integer.valueOf(123)` 会使用缓存池中初始化好的对象。
```java
Integer x = new Integer(123);
Integer y = new Integer(123);
System.out.println(x == y); // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(z == k); // true
```
`valueOf()` 方法的实现比较简单,先判断值是否在缓存池中,如果在的话就直接返回缓存池的对象。
```java
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
```
在 Java 8 中,Integer 缓存池的大小默认为 -128\~127。
```java
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
```
编译器会在自动装箱过程调用 `valueOf()` 方法,也就是说,值相同且在缓存池内的 Integer 对象使用 == 来比较的时候会返回 true。
```java
Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true
```
基本类型对应的缓冲池如下:
- boolean values true and false
- all byte values
- short values between -128 and 127
- int values between -128 and 127
- char in the range \u0000 to \u007F
在 Java 8 的数值类缓冲池中,Integer 的缓冲池 IntegerCache 很特殊,这个缓冲池的下界是 - 128,上界默认是 127,但是上界是可调的。
在启动 jvm 的时候,可以通过 -XX:AutoBoxCacheMax=<size> 来指定缓冲池的大小,该选项在 JVM 初始化的时候会设定一个名为 java.lang.IntegerCache.high 系统属性,然后 IntegerCache 初始化的时候就会读取该系统属性来决定上界。

## 二、String
### 概览
String 被声明为 final,因此它不能被继承。在 Java 8 中,String 内部使用 char 数组存储数据。
```java
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
}
```
但在 Java 9 之后,String 类的实现改用 byte 数组来存储字符串,同时使用 `coder` 来标识使用了哪种编码。
```java
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final byte[] value;
/** The identifier of the encoding used to encode the bytes in {@code value}. */
private final byte coder;
}
```
value 数组被声明为 final,这意味着 value 变量在数组初始化之后就不能再引用其它数组对象了。并且 String 内部没有改变 value 数组的方法,因此可以保证 String 不可变。
推荐阅读:[二哥的 Java 进阶之路:String类源码](https://javabetter.cn/string/string-source.html)
### 字符串不可变的好处
**1. 可以用来作为 HashMap 的 key**
HashMap 的底层数据结构是数组,其键值对在数组中的位置是通过 `(n - 1) & hash` 计算得到的,n 也就是数组的长度,hash 也就是键的哈希值。

如果键是可变的,那么在计算键的哈希值时,哈希值也是不确定的,于是就无法准确地在数组中定位到键值对的位置。
推荐阅读:[HashMap 的源码解读](https://javabetter.cn/collection/hashmap.html)
**2. 字符串常量池的需要**
因为字符串的使用频率非常高,所以 Java 设计者就决定将字符串常量放到一个公共的地方,这个地方叫做字符串常量池(String Pool)。
通过双引号创建的字符串(如 "沉默王二")都会被加入到字符串常量池中,这样就可以减少字符串的创建,节约内存空间。

推荐阅读:[深入理解Java的字符串常量池](https://javabetter.cn/string/constant-pool.html)
**3. 安全性**
String 经常作为参数进行传递,比如说数据库连接中的用户名和密码,如果 String 是可变的,那么在传递的过程中就会存在安全隐患。
推荐阅读:[为什么 Java 字符串是不可变的?](https://javabetter.cn/string/immutable.html)
### String, StringBuffer 和 StringBuilder
**1. 可变性**
- String 不可变
- StringBuffer 和 StringBuilder 可变
**2. 线程安全**
- String 不可变,因此是线程安全的
- StringBuilder 不是线程安全的
- StringBuffer 是线程安全的,内部使用 synchronized 进行同步
推荐阅读:[聊聊 Java StringBuilder和StringBuffer 两兄弟](https://javabetter.cn/string/builder-buffer.html)
### 字符串常量池
字符串常量池(String Pool)保存了所有字符串字面量(literal strings),也就是使用双引号 `""` 创建的字符串对象。当然了,也可以使用 String 的 `intern()` 方法将字符串添加到字符串常量池中。
当一个字符串调用 `intern()` 方法时,如果 String Pool 中已经存在一个字符串和该字符串值相等(使用 `equals()` 方法进行确定),那么就会返回 String Pool 中字符串的引用;否则,就会在 String Pool 中添加一个新的字符串,并返回这个新字符串的引用。
下面示例中,s1 和 s2 采用 `new String()` 的方式新建了两个不同字符串,而 s3 和 s4 是通过 `s1.intern()` 和 `s2.intern()` 方法获取字符串的引用。
`intern()` 会从字符串常量池中返回这个字符串引用,因此 s3 和 s4 引用的是同一个字符串。
```java
String s1 = new String("aaa");
String s2 = new String("aaa");
System.out.println(s1 == s2); // false
String s3 = s1.intern();
String s4 = s2.intern();
System.out.println(s3 == s4); // true
```
如果是采用 "bbb" 这种字面量的形式创建字符串,编译器会自动地将字符串放入 String Pool 中。
```java
String s5 = "bbb";
String s6 = "bbb";
System.out.println(s5 == s6); // true
```
- [字符串常量池](https://javabetter.cn/string/constant-pool.html)
- [详解 String.intern() 方法](https://javabetter.cn/string/intern.html)
### new String("abc")
使用这种方式一共会创建两个字符串对象(前提是 String Pool 中还没有 "abc" 字符串对象)。
- "abc" 属于字符串字面量,因此编译时会在 String Pool 中创建一个字符串对象;
- 使用 new 会在堆中创建一个新的字符串对象,这个新对象在创建的时候,会使用字符串常量池中 "abc" 作为构造方法的参数。
好,我们来创建一个测试类,main 方法中使用这种方式来创建字符串对象。
```java
public class NewStringTest {
public static void main(String[] args) {
String s = new String("abc");
}
}
```
使用 `javap -verbose` 进行反编译,得到以下内容:
```java
// ...
Constant pool:
// ...
#2 = Class #18 // java/lang/String
#3 = String #19 // abc
// ...
#18 = Utf8 java/lang/String
#19 = Utf8 abc
// ...
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=3, locals=2, args_size=1
0: new #2 // class java/lang/String
3: dup
4: ldc #3 // String abc
6: invokespecial #4 // Method java/lang/String."<init>":(Ljava/lang/String;)V
9: astore_1
// ...
```
在 Constant Pool 中,#19 存储了字符串字面量 "abc",#3 是 String Pool 的字符串对象,它指向 #19 这个字符串字面量。
在 main 方法中,0: 行使用 new #2 在堆中创建了一个字符串对象,并且使用 ldc #3 将 String Pool 中的字符串对象作为 String 构造方法的参数。
以下是 String 构造方法的源码,可以看到,在将一个字符串对象作为另一个字符串对象的构造方法参数时,并不会复制 value 数组的内容,而是指向同一个 value 数组。
```java
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
```
> 微信搜索《**沉默王二**》或者微信扫下面的二维码,关注后回复《**java**》即可获取最新的 PDF 版本。

## 三、运算
### 参数传递
Java 的参数是以值传递的形式传入方法中的,而不是引用传递。
这是一个 Dog 类,有一个字段 name、一个构造方法、一个 getName 方法和一个 setName 方法,以及一个 getObjectAddress 方法,用来返回对象的地址。
```java
public class Dog {
String name;
Dog(String name) {
this.name = name;
}
String getName() {
return this.name;
}
void setName(String name) {
this.name = name;
}
String getObjectAddress() {
return super.toString();
}
}
```
然后我们在测试类的 main 方法中创建一个 Dog 对象 dog,并调用 func 方法,将 dog 对象作为参数传入。
```java
class PassByValueExample {
public static void main(String[] args) {
Dog dog = new Dog("A");
func(dog);
System.out.println(dog.getName()); // B
}
private static void func(Dog dog) {
dog.setName("B");
}
}
```
可以看到,dog 的 name 发生了改变,因为调用 func 方法时,传入的是 dog 对象的引用,也就是说,传入的是对象的地址,所以在 func 方法中对对象的字段进行修改,会影响到传入之前的对象。
但如果在方法中将变量引用到其它对象,那么此时方法里和方法外的两个引用其实指向了不同的对象,因此 func 方法中的 `dog = new Dog("B")` 并不会影响 main 方法中的 dog 对象。
```java
public class PassByValueExample {
public static void main(String[] args) {
Dog dog = new Dog("A");
System.out.println(dog.getObjectAddress()); // Dog@4554617c
func(dog);
System.out.println(dog.getObjectAddress()); // Dog@4554617c
System.out.println(dog.getName()); // A
}
private static void func(Dog dog) {
System.out.println(dog.getObjectAddress()); // Dog@4554617c
dog = new Dog("B");
System.out.println(dog.getObjectAddress()); // Dog@74a14482
System.out.println(dog.getName()); // B
}
}
```
因此,在将一个对象作为参数传入另外一个方法时,本质上是将对象的地址以值的方式传递到形参中。
推荐阅读:[Java 到底是值传递还是引用传递](https://javabetter.cn/basic-extra-meal/pass-by-value.html)
### float 与 double
Java 不能隐式向下转型,因为这会使精度降低。
`1.1` 字面量属于 double 类型,不能直接将 `1.1` 赋值给 float 变量,因为这是向下转型。
```java
// float f = 1.1;
```
1.1f 字面量才是 float 类型。
```java
float f = 1.1f;
```
### 隐式类型转换
因为字面量 1 是 int 类型,它比 short 类型精度要高,因此不能隐式地将 int 类型向下转型为 short 类型。
```java
short s1 = 1;
// s1 = s1 + 1;
```
但是使用 += 或者 ++ 运算符会执行隐式类型转换。
```java
s1 += 1;
s1++;
```
上面的语句相当于将 s1 + 1 的计算结果进行了向下转型:
```java
s1 = (short) (s1 + 1);
```
推荐阅读:[自动类型转换与强制类型转换](https://javabetter.cn/basic-grammar/type-cast.html)
### switch
从 Java 7 开始,可以在 switch 条件判断语句中使用 String 对象。
```java
String s = "a";
switch (s) {
case "a":
System.out.println("aaa");
break;
case "b":
System.out.println("bbb");
break;
}
```
推荐阅读:[switch 语句的介绍](https://javabetter.cn/basic-grammar/flow-control.html#_02%E3%80%81switch-%E8%AF%AD%E5%8F%A5)
## 四、关键字
### final
#### 1.变量
使用 final 修饰的变量被称为常量,常量在定义时必须进行初始化,并且初始化后值不可改变。
- 对于基本数据类型,final 修饰后的变量值不可改变。
- 对于引用数据类型,final 修饰后的引用不变,也就事不能引用其它对象,但是被引用的对象本身是可以修改的。
```java
final int x = 1;
// x = 2; // cannot assign value to final variable 'x'
final A y = new A();
y.a = 1;
```
#### 2.方法
final 修饰的方法不能被子类重写。
#### 3. 类
final 修饰的类不允许被继承。
推荐阅读:[一文彻底搞懂 Java final 关键字](https://javabetter.cn/oo/final.html)
### static
#### 1.静态变量
- 静态变量:又称类变量,也就是通过 static 关键字修饰的变量,这个变量是属于类的,类所有的实例都共享静态变量,可以直接通过类名来访问静态变量。静态变量在内存中只有一份。
- 实例变量:或者叫成员变量,每创建一个实例就会产生一个实例变量,它与该实例同生共死。
```java
public class A {
private int x; // 实例变量
private static int y; // 静态变量
public static void main(String[] args) {
// int x = A.x; // Non-static field 'x' cannot be referenced from a static context
A a = new A();
int x = a.x;
int y = A.y;
}
}
```
#### 2.静态方法
static 修饰的方法被称为静态方法,它在类加载的时候就存在了,它不依赖于任何实例。
但 static 不能用来修饰抽象方法,因为 abstract 方法需要子类重写并提供具体实现,而 static 方法是静态的,无法被子类重写,这使得 static 和 abstract 修饰符是冲突的。
```java
public abstract class A {
public static void func1(){
}
// public abstract static void func2(); // Illegal combination of modifiers: 'abstract' and 'static'
}
```
静态方法只能访问所属类的静态字段和静态方法,并且静态方法中不能有 this 和 super 关键字,因为这两个关键字与具体的对象关联。
```java
public class A {
private static int x;
private int y;
public static void func1(){
int a = x;
// int b = y; // Non-static field 'y' cannot be referenced from a static context
// int b = this.y; // 'A.this' cannot be referenced from a static context
}
}
```
#### 3.静态代码块
静态代码块在类初始化时运行一次。
```java
public class A {
static {
System.out.println("123");
}
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
}
}
```
可以用 static 代码块来初始化一些静态变量,它会优先于 main 方法执行。
```
123
```
#### 4.静态内部类
非静态内部类依赖于外部类的实例,也就是说需要先创建外部类的实例,才能用这个实例去创建非静态内部类。而静态内部类不需要,可以直接实例化。
```java
public class OuterClass {
class InnerClass {
}
static class StaticInnerClass {
}
public static void main(String[] args) {
// InnerClass innerClass = new InnerClass(); // 'OuterClass.this' cannot be referenced from a static context
OuterClass outerClass = new OuterClass();
InnerClass innerClass = outerClass.new InnerClass();
StaticInnerClass staticInnerClass = new StaticInnerClass();
}
}
```
但静态内部类不能访问外部类的非静态变量和方法。
#### 5.静态导包
在使用静态变量和静态方法时不用再指明 ClassName,从而简化代码,但可读性大大降低,不推荐。
```java
import static com.xxx.ClassName.*
```
#### 6.代码的初始化顺序
静态变量和静态代码块优先于实例变量和普通代码块,而静态变量和静态代码块的初始化顺序取决于它们在代码中的顺序。
```java
public static String staticField = "静态变量";
static {
System.out.println("静态语句块");
}
public String field = "实例变量";
{
System.out.println("普通语句块");
}
```
最后才是构造方法的初始化。
```java
public InitialOrderTest() {
System.out.println("构造方法");
}
```
存在继承的情况下,初始化顺序为:
- 父类(静态变量、静态语句块)
- 子类(静态变量、静态语句块)
- 父类(实例变量、普通语句块)
- 父类(构造方法)
- 子类(实例变量、普通语句块)
- 子类(构造方法)
推荐阅读:[详解 Java static 关键字的作用](https://javabetter.cn/oo/static.html)
> 微信搜索《**沉默王二**》或者微信扫下面的二维码,关注后回复《**java**》即可获取最新的 PDF 版本。

## 五、Object 通用方法
### 概览
下面👇🏻这些方法都挺常用的,先看个大概,然后我们来挑一些使用频率非常高的方法做一个系统化地介绍。
```java
public native int hashCode()
public boolean equals(Object obj)
protected native Object clone() throws CloneNotSupportedException
public String toString()
public final native Class<?> getClass()
protected void finalize() throws Throwable {}
public final native void notify()
public final native void notifyAll()
public final native void wait(long timeout) throws InterruptedException
public final void wait(long timeout, int nanos) throws InterruptedException
public final void wait() throws InterruptedException
```
### equals()
#### 1. 等价关系
两个对象具有等价关系,需要满足以下 4 个条件:
①、对称性
```java
x.equals(y) == y.equals(x); // true
```
②、传递性
```java
if (x.equals(y) && y.equals(z))
x.equals(z); // true;
```
③、一致性
多次调用 equals() 方法结果不变
```java
x.equals(y) == x.equals(y); // true
```
④、与 null 的比较
对任何不是 null 的对象 x 调用 x.equals(null) 结果都为 false
```java
x.equals(null); // false;
```
#### 2. 等价与相等
- 对于基本数据类型,可以使用 == 判断两个值是否相等。
- 对于引用数据类型,可以使用 == 判断两个变量是否引用了同一个对象,而 `equals()` 方法用于判断引用的对象是否等价。
```java
Integer x = new Integer(1);
Integer y = new Integer(1);
System.out.println(x.equals(y)); // true
System.out.println(x == y); // false
```
#### 3. 如何实现equals方法
①、检查是否为同一个对象的引用,如果是直接返回 true;
②、检查是否是同一类型,如果不是,直接返回 false;
③、转型后判断关键字段是否相等。
```java
public class EqualExample {
private int x;
private int y;
private int z;
public EqualExample(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EqualExample that = (EqualExample) o;
if (x != that.x) return false;
if (y != that.y) return false;
return z == that.z;
}
}
```
### hashCode()
`hashCode()` 方法用于返回对象的哈希值,而 `equals()` 用来判断两个对象是否等价。等价的两个对象哈希值一定相同,但是哈希值相同的两个对象不一定等价,因为哈希值的计算具有随机性,两个值不同的对象可能计算出相同的哈希值。
在重写 `equals()` 方法时应该重写 `hashCode()` 方法,保证等价的两个对象哈希值也相等。
HashSet 和 HashMap 等集合类使用了 `hashCode()` 方法来计算对象应该存储的位置(底层数据结构为数组),因此要将对象添加到这些集合类中,需要让对应的类实现 `hashCode()` 方法。
下面的代码中,新建了两个等价的对象,并将它们添加到 HashSet 中。我们希望将这两个对象当成一样的,只在集合中添加一个。但是 EqualExample 没有实现 `hashCode()` 方法,因此这两个对象的哈希值是不同的,最终导致集合添加了两个等价的对象。
```java
EqualExample e1 = new EqualExample(1, 1, 1);
EqualExample e2 = new EqualExample(1, 1, 1);
System.out.println(e1.equals(e2)); // true
HashSet<EqualExample> set = new HashSet<>();
set.add(e1);
set.add(e2);
System.out.println(set.size()); // 2
```
理想的哈希函数(方法/算法)应当具有均匀性,即不相等的对象应当均匀分布到所有可能的哈希值上。
这就要求了哈希函数要把所有域(字段)的值都考虑进来。可以将每个域都当成 R 进制的某一位,然后组成一个 R 进制的整数。
R 一般取 31,因为它是一个奇素数,如果是偶数的话,当出现乘法溢出,信息就会丢失,因为与 2 相乘相当于向左移一位,最左边的位丢失。
并且一个数与 31 相乘可以转换成移位和减法:`31*x == (x<<5)-x`,编译器会自动进行这个优化。
```java
@Override
public int hashCode() {
int result = 17;
result = 31 * result + x;
result = 31 * result + y;
result = 31 * result + z;
return result;
}
```
### toString()
默认返回 `ToStringExample@4554617c` 这种形式,其中 @ 后面的数值为哈希值(散列码)的无符号十六进制表示。
```java
public class ToStringExample {
private int number;
public ToStringExample(int number) {
this.number = number;
}
}
```
测试一下:
```java
ToStringExample example = new ToStringExample(123);
System.out.println(example.toString());
```
输出结果:
```html
ToStringExample@4554617c
```
### clone()
#### 1. cloneable 接口
`clone()` 是 Object 的 protected 方法,它不是 public,因此如果一个类没有显式重写 `clone()`,其它类就不能直接调用该类实例的 `clone()` 方法。
```java
public class CloneExample {
private int a;
private int b;
}
```
尝试直接调用 `clone()` 方法,编译器提示错误:
```java
CloneExample e1 = new CloneExample();
// CloneExample e2 = e1.clone(); // 'clone()' has protected access in 'java.lang.Object'
```
好,这次重写 `clone()` 方法:
```java
public class CloneExample {
private int a;
private int b;
@Override
public CloneExample clone() throws CloneNotSupportedException {
return (CloneExample)super.clone();
}
}
```
再次尝试调用 `clone()` 方法:
```java
CloneExample e1 = new CloneExample();
try {
CloneExample e2 = e1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
```
输出结果:
```html
java.lang.CloneNotSupportedException: CloneExample
```
哦哦,编译通过了,但运行时抛出 CloneNotSupportedException,这是因为 CloneExample 没有实现 Cloneable 接口。
需要注意的是,`clone()` 方法并不是 Cloneable 接口的方法,而是 Object 的 protected 方法。
Cloneable 接口只是规定(约束),规定一个类如果没有实现 Cloneable 接口就直接调用了 `clone()` 方法,就会抛出 CloneNotSupportedException。
```java
public class CloneExample implements Cloneable {
private int a;
private int b;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
```
#### 2. 浅拷贝
浅拷贝:复制对象的基本数据类型成员变量,和引用数据类型成员变量的引用,导致新对象和原对象共享同一引用对象。
```java
public class ShallowCloneExample implements Cloneable {
private int[] arr;
public ShallowCloneExample() {
arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
public void set(int index, int value) {
arr[index] = value;
}
public int get(int index) {
return arr[index];
}
@Override
protected ShallowCloneExample clone() throws CloneNotSupportedException {
return (ShallowCloneExample) super.clone();
}
}
```
进行浅拷贝,改变 e1 的 arr 数组,e2 的 arr 数组也会改变。
```java
ShallowCloneExample e1 = new ShallowCloneExample();
ShallowCloneExample e2 = null;
try {
e2 = e1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
e1.set(2, 222);
System.out.println(e2.get(2)); // 222
```
#### 3. 深拷贝
深拷贝:不仅复制对象的基本数据类型成员变量,还递归复制引用类型成员变量所引用的对象,使得新对象和原对象完全独立。
```java
public class DeepCloneExample implements Cloneable {
private int[] arr;
public DeepCloneExample() {
arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
public void set(int index, int value) {
arr[index] = value;
}
public int get(int index) {
return arr[index];
}
@Override
protected DeepCloneExample clone() throws CloneNotSupportedException {
DeepCloneExample result = (DeepCloneExample) super.clone();
result.arr = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result.arr[i] = arr[i];
}
return result;
}
}
```
进行深拷贝,改变 e1 的 arr 数组,e2 的 arr 数组不会改变。
```java
DeepCloneExample e1 = new DeepCloneExample();
DeepCloneExample e2 = null;
try {
e2 = e1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
e1.set(2, 222);
System.out.println(e2.get(2)); // 2
```
#### 4. clone() 的替代方案
使用 `clone()` 方法来拷贝一个对象既复杂又有风险,一需要类型转换,二可能抛出异常。
Effective Java 一书上讲到,最好不要去使用 `clone()`,可以使用拷贝构造方法或者拷贝工厂来拷贝一个对象。
```java
public class CloneConstructorExample {
private int[] arr;
public CloneConstructorExample() {
arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
public CloneConstructorExample(CloneConstructorExample original) {
arr = new int[original.arr.length];
for (int i = 0; i < original.arr.length; i++) {
arr[i] = original.arr[i];
}
}
public void set(int index, int value) {
arr[index] = value;
}
public int get(int index) {
return arr[index];
}
}
```