在Java編程中,有些知識(shí) 并不能僅通過(guò)語(yǔ)言規(guī)范或者標(biāo)準(zhǔn)API文檔就能學(xué)到的。在本文中,我會(huì)盡量收集一些最常用的習(xí)慣用法,特別是很難猜到的用法。
我把本文的所有代碼都放在公共場(chǎng)所里。你可以根據(jù)自己的喜好去復(fù)制和修改任意的代碼片段,不需要任何的憑證。
實(shí)現(xiàn)equals()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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(other.name) && birthYear == other.birthYear && Arrays.equals(raw, other.raw); } public int hashCode() { ... } } |
參數(shù)必須是Object類型,不能是外圍類。
foo.equals(null) 必須返回false,不能拋NullPointerException。(注意,null instanceof 任意類 總是返回false,因此上面的代碼可以運(yùn)行。)
基本類型域(比如,int)的比較使用 == ,基本類型數(shù)組域的比較使用Arrays.equals()。
覆蓋equals()時(shí),記得要相應(yīng)地覆蓋 hashCode(),與 equals() 保持一致。
參考: java.lang.Object.equals(Object)。
實(shí)現(xiàn)hashCode()
1
2
3
4
5
6
7
8
9
10
|
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) { ... } } |
當(dāng)x和y兩個(gè)對(duì)象具有x.equals(y) == true ,你必須要確保x.hashCode() == y.hashCode()。
根據(jù)逆反命題,如果x.hashCode() != y.hashCode(),那么x.equals(y) == false 必定成立。
你不需要保證,當(dāng)x.equals(y) == false時(shí),x.hashCode() != y.hashCode()。但是,如果你可以盡可能地使它成立的話,這會(huì)提高哈希表的性能。
hashCode()最簡(jiǎn)單的合法實(shí)現(xiàn)就是簡(jiǎn)單地return 0;雖然這個(gè)實(shí)現(xiàn)是正確的,但是這會(huì)導(dǎo)致HashMap這些數(shù)據(jù)結(jié)構(gòu)運(yùn)行得很慢。
實(shí)現(xiàn)compareTo()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Person implements Comparable< Person > { String firstName; String lastName; int birthdate; // Compare by firstName, break ties by lastName, finally break ties by birthdate public int compareTo(Person other) { if (firstName.compareTo(other.firstName) != 0) return firstName.compareTo(other.firstName); else if (lastName.compareTo(other.lastName) != 0) return lastName.compareTo(other.lastName); else if (birthdate < other.birthdate ) return -1; else if (birthdate > other.birthdate) return 1; else return 0; } } |
總是實(shí)現(xiàn)泛型版本 Comparable 而不是實(shí)現(xiàn)原始類型 Comparable 。因?yàn)檫@樣可以節(jié)省代碼量和減少不必要的麻煩。
只關(guān)心返回結(jié)果的正負(fù)號(hào)(負(fù)/零/正),它們的大小不重要。
Comparator.compare()的實(shí)現(xiàn)與這個(gè)類似。
實(shí)現(xiàn)clone()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Values implements Cloneable { String abc; double foo; int[] bars; Date hired; public Values clone() { try { Values result = (Values)super.clone(); result.bars = result.bars.clone(); result.hired = result.hired.clone(); return result; } catch (CloneNotSupportedException e) { // Impossible throw new AssertionError(e); } } } |
使用 super.clone() 讓Object類負(fù)責(zé)創(chuàng)建新的對(duì)象。
基本類型域都已經(jīng)被正確地復(fù)制了。同樣,我們不需要去克隆String和BigInteger等不可變類型。
手動(dòng)對(duì)所有的非基本類型域(對(duì)象和數(shù)組)進(jìn)行深度復(fù)制(deep copy)。
實(shí)現(xiàn)了Cloneable的類,clone()方法永遠(yuǎn)不要拋CloneNotSupportedException。因此,需要捕獲這個(gè)異常并忽略它,或者使用不受檢異常(unchecked exception)包裝它。
不使用Object.clone()方法而是手動(dòng)地實(shí)現(xiàn)clone()方法是可以的也是合法的。
使用StringBuilder或StringBuffer
1
2
3
4
5
6
7
8
9
10
11
|
// join(["a", "b", "c"]) -> "a and b and c" String join(List< String > strs) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : strs) { if (first) first = false; else sb.append(" and "); sb.append(s); } return sb.toString(); } |
不要像這樣使用重復(fù)的字符串連接:s += item ,因?yàn)樗臅r(shí)間效率是O(n^2)。
使用StringBuilder或者StringBuffer時(shí),可以使用append()方法添加文本和使用toString()方法去獲取連接起來(lái)的整個(gè)文本。
優(yōu)先使用StringBuilder,因?yàn)樗臁tringBuffer的所有方法都是同步的,而你通常不需要同步的方法。
生成一個(gè)范圍內(nèi)的隨機(jī)整數(shù)
1
2
3
4
5
|
Random rand = new Random(); // Between 1 and 6, inclusive int diceRoll() { return rand.nextInt(6) + 1; } |
總是使用Java API方法去生成一個(gè)整數(shù)范圍內(nèi)的隨機(jī)數(shù)。
不要試圖去使用 Math.abs(rand.nextInt()) % n 這些不確定的用法,因?yàn)樗慕Y(jié)果是有偏差的。此外,它的結(jié)果值有可能是負(fù)數(shù),比如當(dāng)rand.nextInt() == Integer.MIN_VALUE時(shí)就會(huì)如此。
使用Iterator.remove()
1
2
3
4
5
6
7
|
void filter(List< String > list) { for (Iterator< String > iter = list.iterator(); iter.hasNext(); ) { String item = iter.next(); if (...) iter.remove(); } } |
remove()方法作用在next()方法最近返回的條目上。每個(gè)條目只能使用一次remove()方法。
返轉(zhuǎn)字符串
1
2
3
|
String reverse(String s) { return new StringBuilder(s).reverse().toString(); } |
這個(gè)方法可能應(yīng)該加入Java標(biāo)準(zhǔn)庫(kù)。
啟動(dòng)一條線程
下面的三個(gè)例子使用了不同的方式完成了同樣的事情。
實(shí)現(xiàn)Runnnable的方式:
1
2
3
4
5
6
7
8
|
void startAThread0() { new Thread(new MyRunnable()).start(); } class MyRunnable implements Runnable { public void run() { ... } } |
繼承Thread的方式:
1
2
3
4
5
6
7
8
|
void startAThread1() { new MyThread().start(); } class MyThread extends Thread { public void run() { ... } } |
匿名繼承Thread的方式:
1
2
3
4
5
6
7
|
void startAThread2() { new Thread() { public void run() { ... } }.start(); } |
不要直接調(diào)用run()方法。總是調(diào)用Thread.start()方法,這個(gè)方法會(huì)創(chuàng)建一條新的線程并使新建的線程調(diào)用run()。
使用try-finally
I/O流例子:
1
2
3
4
5
6
7
8
|
void writeStuff() throws IOException { OutputStream out = new FileOutputStream(...); try { out.write(...); } finally { out.close(); } } |
鎖例子:
1
2
3
4
5
6
7
8
|
void doWithLock(Lock lock) { lock.acquire(); try { ... } finally { lock.release(); } } |
如果try之前的語(yǔ)句運(yùn)行失敗并且拋出異常,那么finally語(yǔ)句塊就不會(huì)執(zhí)行。但無(wú)論怎樣,在這個(gè)例子里不用擔(dān)心資源的釋放。
如果try語(yǔ)句塊里面的語(yǔ)句拋出異常,那么程序的運(yùn)行就會(huì)跳到finally語(yǔ)句塊里執(zhí)行盡可能多的語(yǔ)句,然后跳出這個(gè)方法(除非這個(gè)方法還有另一個(gè)外圍的finally語(yǔ)句塊)。
從輸入流里讀取字節(jié)數(shù)據(jù)
1
2
3
4
5
6
7
8
9
10
11
|
InputStream in = (...); try { while (true) { int b = in.read(); if (b == -1) break; (... process b ...) } } finally { in.close(); } |
read()方法要么返回下一次從流里讀取的字節(jié)數(shù)(0到255,包括0和255),要么在達(dá)到流的末端時(shí)返回-1。
從輸入流里讀取塊數(shù)據(jù)
1
2
3
4
5
6
7
8
9
10
11
12
|
InputStream in = (...); try { byte[] buf = new byte[100]; while (true) { int n = in.read(buf); if (n == -1) break; (... process buf with offset=0 and length=n ...) } } finally { in.close(); } |
要記住的是,read()方法不一定會(huì)填滿整個(gè)buf,所以你必須在處理邏輯中考慮返回的長(zhǎng)度。
從文件里讀取文本
1
2
3
4
5
6
7
8
9
10
11
12
|
BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(...), "UTF-8")); try { while (true) { String line = in.readLine(); if (line == null) break; (... process line ...) } } finally { in.close(); } |
BufferedReader對(duì)象的創(chuàng)建顯得很冗長(zhǎng)。這是因?yàn)镴ava把字節(jié)和字符當(dāng)成兩個(gè)不同的概念來(lái)看待(這與C語(yǔ)言不同)。
你可以使用任何類型的InputStream來(lái)代替FileInputStream,比如socket。
當(dāng)達(dá)到流的末端時(shí),BufferedReader.readLine()會(huì)返回null。
要一次讀取一個(gè)字符,使用Reader.read()方法。
你可以使用其他的字符編碼而不使用UTF-8,但最好不要這樣做。
向文件里寫文本
1
2
3
4
5
6
7
8
9
|
PrintWriter out = new PrintWriter( new OutputStreamWriter(new FileOutputStream(...), "UTF-8")); try { out.print("Hello "); out.print(42); out.println(" world!"); } finally { out.close(); } |
Printwriter對(duì)象的創(chuàng)建顯得很冗長(zhǎng)。這是因?yàn)镴ava把字節(jié)和字符當(dāng)成兩個(gè)不同的概念來(lái)看待(這與C語(yǔ)言不同)。
就像System.out,你可以使用print()和println()打印多種類型的值。
你可以使用其他的字符編碼而不使用UTF-8,但最好不要這樣做。
預(yù)防性檢測(cè)(Defensive checking)數(shù)值
1
2
3
4
5
6
7
8
9
10
|
int factorial(int n) { if (n < 0 ) throw new IllegalArgumentException("Undefined"); else if (n >= 13) throw new ArithmeticException("Result overflow"); else if (n == 0) return 1; else return n * factorial(n - 1); } |
不要認(rèn)為輸入的數(shù)值都是正數(shù)、足夠小的數(shù)等等。要顯式地檢測(cè)這些條件。
一個(gè)設(shè)計(jì)良好的函數(shù)應(yīng)該對(duì)所有可能性的輸入值都能夠正確地執(zhí)行。要確保所有的情況都考慮到了并且不會(huì)產(chǎn)生錯(cuò)誤的輸出(比如溢出)。
預(yù)防性檢測(cè)對(duì)象
1
2
3
4
5
|
int findIndex(List< String > list, String target) { if (list == null || target == null) throw new NullPointerException(); ... } |
不要認(rèn)為對(duì)象參數(shù)不會(huì)為空(null)。要顯式地檢測(cè)這個(gè)條件。
預(yù)防性檢測(cè)數(shù)組索引
1
2
3
4
5
6
7
|
void frob(byte[] b, int index) { if (b == null) throw new NullPointerException(); if (index < 0 || index >= b.length) throw new IndexOutOfBoundsException(); ... } |
不要認(rèn)為所以給的數(shù)組索引不會(huì)越界。要顯式地檢測(cè)它。
預(yù)防性檢測(cè)數(shù)組區(qū)間
1
2
3
4
5
6
7
8
|
void frob(byte[] b, int off, int len) { if (b == null) throw new NullPointerException(); if (off < 0 || off > b.length || len < 0 || b.length - off < len) throw new IndexOutOfBoundsException(); ... } |
不要認(rèn)為所給的數(shù)組區(qū)間(比如,從off開(kāi)始,讀取len個(gè)元素)是不會(huì)越界。要顯式地檢測(cè)它。
填充數(shù)組元素
使用循環(huán):
1
2
3
4
|
// Fill each element of array 'a' with 123 byte[] a = (...); for (int i = 0; i < a.length; i++) a[i] = 123; |
(優(yōu)先)使用標(biāo)準(zhǔn)庫(kù)的方法:
Arrays.fill(a, (byte)123);
復(fù)制一個(gè)范圍內(nèi)的數(shù)組元素
使用循環(huán):
1
2
3
4
5
6
7
|
// Copy 8 elements from array 'a' starting at offset 3 // to array 'b' starting at offset 6, // assuming 'a' and 'b' are distinct arrays byte[] a = (...); byte[] b = (...); for (int i = 0; i < 8; i++) b[6 + i] = a[3 + i]; |
(優(yōu)先)使用標(biāo)準(zhǔn)庫(kù)的方法:
System.arraycopy(a, 3, b, 6, 8);
調(diào)整數(shù)組大小
使用循環(huán)(擴(kuò)大規(guī)模):
1
2
3
4
5
6
|
// Make array 'a' larger to newLen byte[] a = (...); byte[] b = new byte[newLen]; for (int i = 0; i < a.length; i++) // Goes up to length of A b[i] = a[i]; a = b; |
使用循環(huán)(減小規(guī)模):
1
2
3
4
5
6
|
// Make array 'a' smaller to newLen byte[] a = (...); byte[] b = new byte[newLen]; for (int i = 0; i < b.length; i++) // Goes up to length of B b[i] = a[i]; a = b; |
(優(yōu)先)使用標(biāo)準(zhǔn)庫(kù)的方法:
1
|
a = Arrays.copyOf(a, newLen); |
把4個(gè)字節(jié)包裝(packing)成一個(gè)int
1
2
3
4
5
6
7
8
9
10
11
12
13
|
int packBigEndian(byte[] b) { return (b[0] & 0xFF) << 24 | (b[1] & 0xFF) << 16 | (b[2] & 0xFF) << 8 | (b[3] & 0xFF) << 0; } int packLittleEndian(byte[] b) { return (b[0] & 0xFF) << 0 | (b[1] & 0xFF) << 8 | (b[2] & 0xFF) << 16 | (b[3] & 0xFF) << 24; } |
把int分解(Unpacking)成4個(gè)字節(jié)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
byte[] unpackBigEndian(int x) { return new byte[] { (byte)(x >>> 24), (byte)(x >>> 16), (byte)(x >>> 8), (byte)(x >>> 0) }; } byte[] unpackLittleEndian(int x) { return new byte[] { (byte)(x >>> 0), (byte)(x >>> 8), (byte)(x >>> 16), (byte)(x >>> 24) }; } |
總是使用無(wú)符號(hào)右移操作符(>>>)對(duì)位進(jìn)行包裝(packing),不要使用算術(shù)右移操作符(>>)。