自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java習慣用法總結(jié)

移動開發(fā)
在Java編程中,有些知識 并不能僅通過語言規(guī)范或者標準API文檔就能學到的。在本文中,我會盡量收集一些最常用的習慣用法,特別是很難猜到的用法。(Joshua Bloch的《Effective Java》對這個話題給出了更詳盡的論述,可以從這本書里學習更多的用法。)

在Java編程中,有些知識 并不能僅通過語言規(guī)范或者標準API文檔就能學到的。在本文中,我會盡量收集一些最常用的習慣用法,特別是很難猜到的用法。(Joshua Bloch的《Effective Java》對這個話題給出了更詳盡的論述,可以從這本書里學習更多的用法。)

我把本文的所有代碼都放在公共場所里。你可以根據(jù)自己的喜好去復制和修改任意的代碼片段,不需要任何的憑證。

實現(xiàn)equals()

  1. class Person { 
  2.   String name; 
  3.   int birthYear; 
  4.   byte[] raw; 
  5.   
  6.   public boolean equals(Object obj) { 
  7.     if (!obj instanceof Person) 
  8.       return false; 
  9.   
  10.     Person other = (Person)obj; 
  11.     return name.equals(other.name) 
  12.         && birthYear == other.birthYear 
  13.         && Arrays.equals(raw, other.raw); 
  14.   } 
  15.   
  16.   public int hashCode() { ... } 

參數(shù)必須是Object類型,不能是外圍類。

foo.equals(null) 必須返回false,不能拋NullPointerException。(注意,null instanceof 任意類 總是返回false,因此上面的代碼可以運行。)

基本類型域(比如,int)的比較使用 == ,基本類型數(shù)組域的比較使用Arrays.equals()。

覆蓋equals()時,記得要相應地覆蓋 hashCode(),與 equals() 保持一致。

參考: java.lang.Object.equals(Object)。

實現(xiàn)hashCode()

  1. class Person { 
  2.   String a; 
  3.   Object b; 
  4.   byte c; 
  5.   int[] d; 
  6.   
  7.   public int hashCode() { 
  8.     return a.hashCode() + b.hashCode() + c + Arrays.hashCode(d); 
  9.   } 
  10.   
  11.   public boolean equals(Object o) { ... } 

當x和y兩個對象具有x.equals(y) == true ,你必須要確保x.hashCode() == y.hashCode()。

根據(jù)逆反***,如果x.hashCode() != y.hashCode(),那么x.equals(y) == false 必定成立。

你不需要保證,當x.equals(y) == false時,x.hashCode() != y.hashCode()。但是,如果你可以盡可能地使它成立的話,這會提高哈希表的性能。

hashCode()最簡單的合法實現(xiàn)就是簡單地return 0;雖然這個實現(xiàn)是正確的,但是這會導致HashMap這些數(shù)據(jù)結(jié)構運行得很慢。

參考:java.lang.Object.hashCode()

實現(xiàn)compareTo()

  1. class Person implements Comparable<Person> { 
  2.   String firstName; 
  3.   String lastName; 
  4.   int birthdate; 
  5.   
  6.   // Compare by firstName, break ties by lastName, finally break ties by birthdate 
  7.   public int compareTo(Person other) { 
  8.     if (firstName.compareTo(other.firstName) != 0) 
  9.       return firstName.compareTo(other.firstName); 
  10.     else if (lastName.compareTo(other.lastName) != 0) 
  11.       return lastName.compareTo(other.lastName); 
  12.     else if (birthdate < other.birthdate) 
  13.       return -1; 
  14.     else if (birthdate > other.birthdate) 
  15.       return 1; 
  16.     else 
  17.       return 0; 
  18.   } 

總是實現(xiàn)泛型版本 Comparable 而不是實現(xiàn)原始類型 Comparable 。因為這樣可以節(jié)省代碼量和減少不必要的麻煩。

只關心返回結(jié)果的正負號(負/零/正),它們的大小不重要。

Comparator.compare()的實現(xiàn)與這個類似。

參考:java.lang.Comparable。

#p#

實現(xiàn)clone()

  1. class Values implements Cloneable { 
  2.   String abc; 
  3.   double foo; 
  4.   int[] bars; 
  5.   Date hired; 
  6.   
  7.   public Values clone() { 
  8.     try { 
  9.       Values result = (Values)super.clone(); 
  10.       result.bars = result.bars.clone(); 
  11.       result.hired = result.hired.clone(); 
  12.       return result; 
  13.     } catch (CloneNotSupportedException e) {  // Impossible 
  14.       throw new AssertionError(e); 
  15.     } 
  16.   } 

使用 super.clone() 讓Object類負責創(chuàng)建新的對象。

基本類型域都已經(jīng)被正確地復制了。同樣,我們不需要去克隆String和BigInteger等不可變類型。

手動對所有的非基本類型域(對象和數(shù)組)進行深度復制(deep copy)。

實現(xiàn)了Cloneable的類,clone()方法永遠不要拋CloneNotSupportedException。因此,需要捕獲這個異常并忽略它,或者使用不受檢異常(unchecked exception)包裝它。

不使用Object.clone()方法而是手動地實現(xiàn)clone()方法是可以的也是合法的。

參考:java.lang.Object.clone()、java.lang.Cloneable()。

使用StringBuilder或StringBuffer

  1. // join(["a", "b", "c"]) -> "a and b and c" 
  2. String join(List<String> strs) { 
  3.   StringBuilder sb = new StringBuilder(); 
  4.   boolean first = true; 
  5.   for (String s : strs) { 
  6.     if (first) first = false; 
  7.     else sb.append(" and "); 
  8.     sb.append(s); 
  9.   } 
  10.   return sb.toString(); 

不要像這樣使用重復的字符串連接:s += item ,因為它的時間效率是O(n^2)。

使用StringBuilder或者StringBuffer時,可以使用append()方法添加文本和使用toString()方法去獲取連接起來的整個文本。

優(yōu)先使用StringBuilder,因為它更快。StringBuffer的所有方法都是同步的,而你通常不需要同步的方法。

參考java.lang.StringBuilder、java.lang.StringBuffer。

生成一個范圍內(nèi)的隨機整數(shù)

  1. Random rand = new Random(); 
  2.   
  3. // Between 1 and 6, inclusive 
  4. int diceRoll() { 
  5.   return rand.nextInt(6) + 1; 

總是使用Java API方法去生成一個整數(shù)范圍內(nèi)的隨機數(shù)。

不要試圖去使用 Math.abs(rand.nextInt()) % n 這些不確定的用法,因為它的結(jié)果是有偏差的。此外,它的結(jié)果值有可能是負數(shù),比如當rand.nextInt() == Integer.MIN_VALUE時就會如此。

參考:java.util.Random.nextInt(int)。

使用Iterator.remove()

  1. void filter(List<String> list) { 
  2.   for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) { 
  3.     String item = iter.next(); 
  4.     if (...) 
  5.       iter.remove(); 
  6.   } 

remove()方法作用在next()方法最近返回的條目上。每個條目只能使用一次remove()方法。

參考:java.util.Iterator.remove()。

返轉(zhuǎn)字符串

  1. String reverse(String s) { 
  2.   return new StringBuilder(s).reverse().toString(); 

這個方法可能應該加入Java標準庫。

參考:java.lang.StringBuilder.reverse()

啟動一條線程

下面的三個例子使用了不同的方式完成了同樣的事情。

實現(xiàn)Runnnable的方式:

  1. void startAThread0() { 
  2.   new Thread(new MyRunnable()).start(); 
  3.   
  4. class MyRunnable implements Runnable { 
  5.   public void run() { 
  6.     ... 
  7.   } 

繼承Thread的方式: 

  1. void startAThread1() { 
  2.   new MyThread().start(); 
  3.   
  4. class MyThread extends Thread { 
  5.   public void run() { 
  6.     ... 
  7.   } 

匿名繼承Thread的方式: 

 

  1. void startAThread2() { 
  2.   new Thread() { 
  3.     public void run() { 
  4.       ... 
  5.     } 
  6.   }.start(); 

不要直接調(diào)用run()方法??偸钦{(diào)用Thread.start()方法,這個方法會創(chuàng)建一條新的線程并使新建的線程調(diào)用run()。

 

參考:java.lang.Thread, java.lang.Runnable。

#p#

使用try-finally

I/O流例子:

  1. void writeStuff() throws IOException { 
  2.   OutputStream out = new FileOutputStream(...); 
  3.   try { 
  4.     out.write(...); 
  5.   } finally { 
  6.     out.close(); 
  7.   } 

鎖例子:

  1. void doWithLock(Lock lock) { 
  2.   lock.acquire(); 
  3.   try { 
  4.     ... 
  5.   } finally { 
  6.     lock.release(); 
  7.   } 

如果try之前的語句運行失敗并且拋出異常,那么finally語句塊就不會執(zhí)行。但無論怎樣,在這個例子里不用擔心資源的釋放。

如果try語句塊里面的語句拋出異常,那么程序的運行就會跳到finally語句塊里執(zhí)行盡可能多的語句,然后跳出這個方法(除非這個方法還有另一個外圍的finally語句塊)。

從輸入流里讀取字節(jié)數(shù)據(jù)

  1. InputStream in = (...); 
  2. try { 
  3.   while (true) { 
  4.     int b = in.read(); 
  5.     if (b == -1) 
  6.       break; 
  7.     (... process b ...) 
  8.   } 
  9. } finally { 
  10.   in.close(); 

read()方法要么返回下一次從流里讀取的字節(jié)數(shù)(0到255,包括0和255),要么在達到流的末端時返回-1。

參考:java.io.InputStream.read()。

從輸入流里讀取塊數(shù)據(jù)

  1. InputStream in = (...); 
  2. try { 
  3.   byte[] buf = new byte[100]; 
  4.   while (true) { 
  5.     int n = in.read(buf); 
  6.     if (n == -1) 
  7.       break; 
  8.     (... process buf with offset=0 and length=n ...) 
  9.   } 
  10. } finally { 
  11.   in.close(); 

要記住的是,read()方法不一定會填滿整個buf,所以你必須在處理邏輯中考慮返回的長度。

參考: java.io.InputStream.read(byte[])、java.io.InputStream.read(byte[], int, int)。

從文件里讀取文本

 

  1. BufferedReader in = new BufferedReader( 
  2.     new InputStreamReader(new FileInputStream(...), "UTF-8")); 
  3. try { 
  4.   while (true) { 
  5.     String line = in.readLine(); 
  6.     if (line == null) 
  7.       break; 
  8.     (... process line ...) 
  9.   } 
  10. } finally { 
  11.   in.close(); 

BufferedReader對象的創(chuàng)建顯得很冗長。這是因為Java把字節(jié)和字符當成兩個不同的概念來看待(這與C語言不同)。

 

你可以使用任何類型的InputStream來代替FileInputStream,比如socket。

當達到流的末端時,BufferedReader.readLine()會返回null。

要一次讀取一個字符,使用Reader.read()方法。

你可以使用其他的字符編碼而不使用UTF-8,但***不要這樣做。

參考:java.io.BufferedReader、java.io.InputStreamReader。

向文件里寫文本

  1. PrintWriter out = new PrintWriter( 
  2.     new OutputStreamWriter(new FileOutputStream(...), "UTF-8")); 
  3. try { 
  4.   out.print("Hello "); 
  5.   out.print(42); 
  6.   out.println(" world!"); 
  7. } finally { 
  8.   out.close(); 

Printwriter對象的創(chuàng)建顯得很冗長。這是因為Java把字節(jié)和字符當成兩個不同的概念來看待(這與C語言不同)。

就像System.out,你可以使用print()和println()打印多種類型的值。

你可以使用其他的字符編碼而不使用UTF-8,但***不要這樣做。

參考:java.io.PrintWriterjava.io.OutputStreamWriter。

預防性檢測(Defensive checking)數(shù)值

  1. int factorial(int n) { 
  2.   if (n < 0) 
  3.     throw new IllegalArgumentException("Undefined"); 
  4.   else if (n >= 13) 
  5.     throw new ArithmeticException("Result overflow"); 
  6.   else if (n == 0) 
  7.     return 1; 
  8.   else 
  9.     return n * factorial(n - 1); 

不要認為輸入的數(shù)值都是正數(shù)、足夠小的數(shù)等等。要顯式地檢測這些條件。

一個設計良好的函數(shù)應該對所有可能性的輸入值都能夠正確地執(zhí)行。要確保所有的情況都考慮到了并且不會產(chǎn)生錯誤的輸出(比如溢出)。

預防性檢測對象

  1. int findIndex(List<String> list, String target) { 
  2.   if (list == null || target == null) 
  3.     throw new NullPointerException(); 
  4.   ... 

不要認為對象參數(shù)不會為空(null)。要顯式地檢測這個條件。

#p#

預防性檢測數(shù)組索引

  1. void frob(byte[] b, int index) { 
  2.   if (b == null) 
  3.     throw new NullPointerException(); 
  4.   if (index < 0 || index >= b.length) 
  5.     throw new IndexOutOfBoundsException(); 
  6.   ... 

不要認為所以給的數(shù)組索引不會越界。要顯式地檢測它。

預防性檢測數(shù)組區(qū)間

  1. void frob(byte[] b, int off, int len) { 
  2.   if (b == null) 
  3.     throw new NullPointerException(); 
  4.   if (off < 0 || off > b.length 
  5.     || len < 0 || b.length - off < len) 
  6.     throw new IndexOutOfBoundsException(); 
  7.   ... 

不要認為所給的數(shù)組區(qū)間(比如,從off開始,讀取len個元素)是不會越界。要顯式地檢測它。

填充數(shù)組元素

使用循環(huán):

  1. // Fill each element of array 'a' with 123 
  2. byte[] a = (...); 
  3. for (int i = 0; i < a.length; i++) 
  4.   a[i] = 123; 

(優(yōu)先)使用標準庫的方法:

  1. Arrays.fill(a, (byte)123); 

參考:java.util.Arrays.fill(T[], T)。

參考:java.util.Arrays.fill(T[], int, int, T)。

復制一個范圍內(nèi)的數(shù)組元素

使用循環(huán): 

  1. // Copy 8 elements from array 'a' starting at offset 3 
  2. // to array 'b' starting at offset 6, 
  3. // assuming 'a' and 'b' are distinct arrays 
  4. byte[] a = (...); 
  5. byte[] b = (...); 
  6. for (int i = 0; i < 8; i++) 
  7.   b[6 + i] = a[3 + i]; 

(優(yōu)先)使用標準庫的方法:

  1. System.arraycopy(a, 3, b, 6, 8); 

參考:java.lang.System.arraycopy(Object, int, Object, int, int)。

調(diào)整數(shù)組大小

使用循環(huán)(擴大規(guī)模):

  1. // Make array 'a' larger to newLen 
  2. byte[] a = (...); 
  3. byte[] b = new byte[newLen]; 
  4. for (int i = 0; i < a.length; i++)  // Goes up to length of A 
  5.   b[i] = a[i]; 
  6. a = b; 

使用循環(huán)(減小規(guī)模):

  1. // Make array 'a' smaller to newLen 
  2. byte[] a = (...); 
  3. byte[] b = new byte[newLen]; 
  4. for (int i = 0; i < b.length; i++)  // Goes up to length of B 
  5.   b[i] = a[i]; 
  6. a = b; 

(優(yōu)先)使用標準庫的方法:

  1. a = Arrays.copyOf(a, newLen); 

參考:java.util.Arrays.copyOf(T[], int)

參考:java.util.Arrays.copyOfRange(T[], int, int)。

把4個字節(jié)包裝(packing)成一個int

  1. int packBigEndian(byte[] b) {  
  2.   return (b[0] & 0xFF) << 24  
  3.        | (b[1] & 0xFF) << 16  
  4.        | (b[2] & 0xFF) <<  8  
  5.        | (b[3] & 0xFF) <<  0;  
  6. }  
  7.    
  8. int packLittleEndian(byte[] b) {  
  9.   return (b[0] & 0xFF) <<  0  
  10.        | (b[1] & 0xFF) <<  8  
  11.        | (b[2] & 0xFF) << 16  
  12.        | (b[3] & 0xFF) << 24;  
  13. }  

把int分解(Unpacking)成4個字節(jié)

  1. byte[] unpackBigEndian(int x) { 
  2.   return new byte[] { 
  3.     (byte)(x >>> 24), 
  4.     (byte)(x >>> 16), 
  5.     (byte)(x >>>  8), 
  6.     (byte)(x >>>  0) 
  7.   }; 
  8.   
  9. byte[] unpackLittleEndian(int x) { 
  10.   return new byte[] { 
  11.     (byte)(x >>>  0), 
  12.     (byte)(x >>>  8), 
  13.     (byte)(x >>> 16), 
  14.     (byte)(x >>> 24) 
  15.   }; 

總是使用無符號右移操作符(>>>)對位進行包裝(packing),不要使用算術右移操作符(>>)。

原文鏈接: nayuki    翻譯: ImportNew.com 進林
譯文鏈接: http://www.importnew.com/15605.html

 

責任編輯:倪明
相關推薦

2017-09-05 09:17:47

Java編程用法總結(jié)

2015-12-28 13:45:53

Windows 10照片應用

2009-12-14 10:03:57

Ruby慣用法

2020-05-07 17:03:49

Python編碼開發(fā)

2011-06-09 15:15:52

RAII

2024-02-01 00:10:21

C++PIMPL編程

2024-02-02 12:42:42

C++Policy模板

2021-06-09 09:49:35

C++RAII語言

2013-12-19 16:26:29

Android ApiAndroid開發(fā)Android SDK

2011-04-12 11:32:31

Oraclerownum用法

2015-12-09 09:51:03

Java高性能

2009-03-10 14:17:53

微軟招聘曝光

2023-01-11 07:14:39

DateUtil用法Hutool

2016-08-29 17:28:53

JavascriptHtmlThis

2013-12-12 17:14:10

Linuxvim

2011-03-16 09:42:27

Oracle臨時表

2011-08-02 17:14:41

iPhone應用 UITableVie

2010-04-28 16:30:52

Oracle case

2009-03-20 14:21:25

程序員性格特點生活習慣

2022-08-10 19:32:14

Java代碼習慣
點贊
收藏

51CTO技術棧公眾號