Java开发者看习惯用法总结-北京尚学堂java培训教程.doc
文本预览下载声明
北京尚学堂提供
在Java编程中,有些知识 并不能仅通过语言规范或者标准API文档就能学到的。在本文中,我会尽量收集一些最常用的习惯用法,特别是很难猜到的用法。(Joshua Bloch的《Effective Java》对这个话题给出了更详尽的论述,可以从这本书里学习更多的用法。)
我把本文的所有代码都放在公共场所里。你可以根据自己的喜好去复制和修改任意的代码片段,不需要任何的凭证。
目录
实现:
equals()
hashCode()
compareTo()
clone()
应用:
StringBuilder/StringBuffer
Random.nextInt(int)
Iterator.remove()
StringBuilder.reverse()
Thread/Runnable
try-finally
输入/输出:
从输入流里读取字节数据
从输入流里读取块数据
从文件里读取文本
向文件里写文本
预防性检测:
数值
对象
数组索引
数组区间
数组:
填充元素
复制一个范围内的数组元素
调整数组大小
包装
个字节包装成一个int
分解成4个字节
实现equals()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 class Person {
??String name;
??int birthYear;
??byte[] raw;
?
??public boolean equals(Object obj) {
????if (!obj instanceof Person)
??????return false;
?
????Person other = (Person)obj;
????return name.equals()
???????? birthYear == other.birthYear
???????? Arrays.equals(raw, other.raw);
??}
?
??public int hashCode() { ... }
} 参数必须是Object类型,不能是外围类。
foo.equals(null) 必须返回false,不能抛NullPointerException。(注意,null instanceof 任意类 总是返回false,因此上面的代码可以运行。)
基本类型域(比如,int)的比较使用 == ,基本类型数组域的比较使用Arrays.equals()。
覆盖equals()时,记得要相应地覆盖 hashCode(),与 equals() 保持一致。
参考:?java.lang.Object.equals(Object)。
实现hashCode()
1
2
3
4
5
6
7
8
9
10
11
12 class Person {
??String a;
??Object b;
??byte c;
??int[] d;
?
??public int hashCode() {
????return a.hashCode() + b.hashCode() + c + Arrays.hashCode(d);
??}
?
??public boolean equals(Object o) { ... }
} 当x和y两个对象具有x.equals(y) == true ,你必须要确保x.hashCode() == y.hashCode()。
根据逆反命题,如果x.hashCode() != y.hashCode(),那么x.equals(y) == false 必定成立。
你不需要保证,当x.equals(y) == false时,x.hashCode() != y.hashCode()。但是,如果你可以尽可能地使它成立的话,这会提高哈希表的性能。
hashCode()最简单的合法实现就是简单地return 0;虽然这个实现是正确的,但是这会导致HashMap这些数据结构运行得很慢。
参考:java.lang.Object.hashCode()。
实现compareTo()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 class Person implements ComparablePerson {
??String firstName;
??String lastName;
??int birthdate;
?
??// Compare by firstName, break ties by lastName, finally break ties by birthdate
??public int compareTo(Person other) {
????if (firstNpar
显示全部