Java開發(fā)程序員必知的Java編程的10種錯(cuò)誤
作為程序員在程序開發(fā)的過程中難免的要出現(xiàn)一些不是自己水平問題二出現(xiàn)的一些常見的錯(cuò)誤。本文就為大家介紹一些常見在Java開發(fā)過程中遇見的一些常見的錯(cuò)誤。
一、常見錯(cuò)誤1:多次拷貝字符串
測試所不能發(fā)現(xiàn)的一個(gè)錯(cuò)誤是生成不可變(immutable)對象的多份拷貝。不可變對象是不可改變的,因此不需要拷貝它。最常用的不可變對象是String。
如果你必須改變一個(gè)String對象的內(nèi)容,你應(yīng)該使用StringBuffer。下面的代碼會(huì)正常工作:
- String s = new String ("Text here");
 
但是,這段代碼性能差,而且沒有必要這么復(fù)雜。你還可以用以下的方式來重寫上面的代碼:
- String temp = "Text here";
 - String s = new String (temp);
 
但是這段代碼包含額外的String,并非完全必要。更好的代碼為:
- String s = "Text here";
 
二、常見錯(cuò)誤2:沒有克隆(clone)返回的對象
封裝(encapsulation)是面向?qū)ο缶幊痰闹匾拍?。不幸的是,Java為不小心打破封裝提供了方便——Java允許返回私有數(shù)據(jù)的引用(reference)。下面的代碼揭示了這一點(diǎn):
- import java.awt.Dimension;
 - /** *//***Example class.The x and y values should never*be negative.*/
 - public class Example...{
 - private Dimension d = new Dimension (0, 0);
 - public Example ()...{ }
 - /** *//*** Set height and width. Both height and width must be nonnegative * or an exception is thrown.*/
 - public synchronized void setValues (int height,int width) throws IllegalArgumentException...{
 - if (height <0 || width <0)
 - throw new IllegalArgumentException();
 - d.height = height;
 - d.width = width;
 - }
 - public synchronized Dimension getValues()...{
 - // Ooops! Breaks encapsulation
 - return d;
 - }
 - }
 
Example類保證了它所存儲(chǔ)的height和width值永遠(yuǎn)非負(fù)數(shù),試圖使用setValues()方法來設(shè)置負(fù)值會(huì)觸發(fā)異常。不幸的是,由于getValues()返回d的引用,而不是d的拷貝,你可以編寫如下的破壞性代碼:
- Example ex = new Example();
 - Dimension d = ex.getValues();
 - d.height = -5;
 - d.width = -10;
 
現(xiàn)在,Example對象擁有負(fù)值了!如果getValues() 的調(diào)用者永遠(yuǎn)也不設(shè)置返回的Dimension對象的width 和height值,那么僅憑測試是不可能檢測到這類的錯(cuò)誤。
不幸的是,隨著時(shí)間的推移,客戶代碼可能會(huì)改變返回的Dimension對象的值,這個(gè)時(shí)候,追尋錯(cuò)誤的根源是件枯燥且費(fèi)時(shí)的事情,尤其是在多線程環(huán)境中。
更好的方式是讓getValues()返回拷貝:
- public synchronized Dimension getValues()...{
 - return new Dimension (d.x, d.y);
 - }
 
現(xiàn)在,Example對象的內(nèi)部狀態(tài)就安全了。調(diào)用者可以根據(jù)需要改變它所得到的拷貝的狀態(tài),但是要修改Example對象的內(nèi)部狀態(tài),必須通過setValues()才可以。
三、常見錯(cuò)誤3:不必要的克隆
我們現(xiàn)在知道了get方法應(yīng)該返回內(nèi)部數(shù)據(jù)對象的拷貝,而不是引用。但是,事情沒有絕對:
- /** *//*** Example class.The value should never * be negative.*/
 - public class Example...{
 - private Integer i = new Integer (0);
 - public Example ()...{ }
 - /** *//*** Set x. x must be nonnegative* or an exception will be thrown*/
 - public synchronized void setValues (int x) throws IllegalArgumentException...{
 - if (x <0)
 - throw new IllegalArgumentException();
 - i = new Integer (x);
 - }
 - public synchronized Integer getValue()...{
 - // We can’t clone Integers so we makea copy this way.
 - return new Integer (i.intValue());
 - }
 - }
 
這段代碼是安全的,但是就象在錯(cuò)誤1#那樣,又作了多余的工作。Integer對象,就象String對象那樣,一旦被創(chuàng)建就是不可變的。因此,返回內(nèi)部Integer對象,而不是它的拷貝,也是安全的。
方法getValue()應(yīng)該被寫為:
- public synchronized Integer getValue()...{
 - // ’i’ is immutable, so it is safe to return it instead of a copy.
 - return i;
 - }
 
Java程序比C++程序包含更多的不可變對象。JDK 所提供的若干不可變類包括:
- ·Boolean
 - ·Byte
 - ·Character
 - ·Class
 - ·Double
 - ·Float
 - ·Integer
 - ·Long
 - ·Short
 - ·String
 - ·大部分的Exception的子類
 
四、常見錯(cuò)誤4:自編代碼來拷貝數(shù)組
Java允許你克隆數(shù)組,但是開發(fā)者通常會(huì)錯(cuò)誤地編寫如下的代碼,問題在于如下的循環(huán)用三行做的事情,如果采用Object的clone方法用一行就可以完成:
- public class Example...{
 - private int[] copy;
 - /** *//*** Save a copy of ’data’. ’data’ cannot be null.*/
 - public void saveCopy (int[] data)...{
 - copy = new int[data.length];
 - for (int i = 0; i
 - copy[i] = data[i];
 - }
 - }
 
這段代碼是正確的,但卻不必要地復(fù)雜。saveCopy()的一個(gè)更好的實(shí)現(xiàn)是:
- void saveCopy (int[] data)...{
 - try...{
 - copy = (int[])data.clone();
 - }catch (CloneNotSupportedException e)...{
 - // Can’t get here.
 - }
 - }
 
如果你經(jīng)??寺?shù)組,編寫如下的一個(gè)工具方法會(huì)是個(gè)好主意:
- static int[] cloneArray (int[] data)...{
 - try...{
 - return(int[])data.clone();
 - }catch(CloneNotSupportedException e)...{
 - // Can’t get here.
 - }
 - }
 
這樣的話,我們的saveCopy看起來就更簡潔了:
- void saveCopy (int[] data)...{
 - copy = cloneArray ( data);
 - }
 
#p#
五、常見錯(cuò)誤5:拷貝錯(cuò)誤的數(shù)據(jù)
有時(shí)候程序員知道必須返回一個(gè)拷貝,但是卻不小心拷貝了錯(cuò)誤的數(shù)據(jù)。由于僅僅做了部分的數(shù)據(jù)拷貝工作,下面的代碼與程序員的意圖有偏差:
- import java.awt.Dimension;
 - /** *//*** Example class. The height and width values should never * be
 - negative. */
 - public class Example...{
 - static final public int TOTAL_VALUES = 10;
 - private Dimension[] d = new Dimension[TOTAL_VALUES];
 - public Example ()...{ }
 - /** *//*** Set height and width. Both height and width must be nonnegative * or an exception will be thrown. */
 - public synchronized void setValues (int index, int height, int width) throws IllegalArgumentException...{
 - if (height <0 || width <0)
 - throw new IllegalArgumentException();
 - if (d[index] == null)
 - d[index] = new Dimension();
 - d[index].height = height;
 - d[index].width = width;
 - }
 - public synchronized Dimension[] getValues()
 - throws CloneNotSupportedException...{
 - return (Dimension[])d.clone();
 - }
 - }
 
這兒的問題在于getValues()方法僅僅克隆了數(shù)組,而沒有克隆數(shù)組中包含的Dimension對象,因此,雖然調(diào)用者無法改變內(nèi)部的數(shù)組使其元素指向不同的Dimension對象,但是調(diào)用者卻可以改變內(nèi)部的數(shù)組元素(也就是Dimension對象)的內(nèi)容。方法getValues()的更好版本為:
- public synchronized Dimension[] getValues() throws CloneNotSupportedException...{
 - Dimension[] copy = (Dimension[])d.clone();
 - for (int i = 0; i
 - // NOTE: Dimension isn’t cloneable.
 - if (d != null)
 - copy[i] = new Dimension (d[i].height, d[i].width);
 - }
 - return copy;
 - }
 
在克隆原子類型數(shù)據(jù)的多維數(shù)組的時(shí)候,也會(huì)犯類似的錯(cuò)誤。原子類型包括int,float等。簡單的克隆int型的一維數(shù)組是正確的,如下所示:
- public void store (int[] data) throws CloneNotSupportedException...{
 - this.data = (int[])data.clone();
 - // OK
 - }
 
拷貝int型的二維數(shù)組更復(fù)雜些。Java沒有int型的二維數(shù)組,因此一個(gè)int型的二維數(shù)組實(shí)際上是一個(gè)這樣的一維數(shù)組:它的類型為int[]。簡單的克隆int[][]型的數(shù)組會(huì)犯與上面例子中g(shù)etValues()方法第一版本同樣的錯(cuò)誤,因此應(yīng)該避免這么做。下面的例子演示了在克隆int型二維數(shù)組時(shí)錯(cuò)誤的和正確的做法:
- public void wrongStore (int[][] data) throws CloneNotSupportedException...{
 - this.data = (int[][])data.clone(); // Not OK!
 - }
 - public void rightStore (int[][] data)...{
 - // OK!
 - this.data = (int[][])data.clone();
 - for (int i = 0; i
 - if (data != null)
 - this.data[i] = (int[])data[i].clone();
 - }
 - }
 
六、常見錯(cuò)誤6:檢查new 操作的結(jié)果是否為null
Java編程新手有時(shí)候會(huì)檢查new操作的結(jié)果是否為null??赡艿臋z查代碼為:
- Integer i = new Integer (400);
 - if (i == null)
 - throw new NullPointerException();
 
檢查當(dāng)然沒什么錯(cuò)誤,但卻不必要,if和throw這兩行代碼完全是浪費(fèi),他們的唯一功用是讓整個(gè)程序更臃腫,運(yùn)行更慢。
C/C++程序員在開始寫java程序的時(shí)候常常會(huì)這么做,這是由于檢查C中malloc()的返回結(jié)果是必要的,不這樣做就可能產(chǎn)生錯(cuò)誤。檢查C++中new操作的結(jié)果可能是一個(gè)好的編程行為,這依賴于異常是否被使能(許多編譯器允許異常被禁止,在這種情況下new操作失敗就會(huì)返回null)。在java 中,new 操作不允許返回null,如果真的返回null,很可能是虛擬機(jī)崩潰了,這時(shí)候即便檢查返回結(jié)果也無濟(jì)于事。
七、常見錯(cuò)誤7:用== 替代.equals
在Java中,有兩種方式檢查兩個(gè)數(shù)據(jù)是否相等:通過使用==操作符,或者使用所有對象都實(shí)現(xiàn)的.equals方法。原子類型(int, flosat, char 等)不是對象,因此他們只能使用==操作符,如下所示:
- int x = 4;
 - int y = 5;
 - if (x == y)
 - System.out.println ("Hi");
 - // This ’if’ test won’t compile.
 - if (x.equals (y))
 - System.out.println ("Hi");
 
對象更復(fù)雜些,==操作符檢查兩個(gè)引用是否指向同一個(gè)對象,而equals方法則實(shí)現(xiàn)更專門的相等性檢查。
更顯得混亂的是由java.lang.Object 所提供的缺省的equals方法的實(shí)現(xiàn)使用==來簡單的判斷被比較的兩個(gè)對象是否為同一個(gè)。
許多類覆蓋了缺省的equals方法以便更有用些,比如String類,它的equals方法檢查兩個(gè)String對象是否包含同樣的字符串,而Integer的equals方法檢查所包含的int值是否相等。
  大部分時(shí)候,在檢查兩個(gè)對象是否相等的時(shí)候你應(yīng)該使用equals方法,而對于原子類型的數(shù)據(jù),你用該使用==操作符
#p#
八、常見錯(cuò)誤8:混淆原子操作和非原子操作
Java保證讀和寫32位數(shù)或者更小的值是原子操作,也就是說可以在一步完成,因而不可能被打斷,因此這樣的讀和寫不需要同步。以下的代碼是線程安全(thread safe)的:
- public class Example...{
 - private int value; // More code here...
 - public void set (int x)...{
 - // NOTE: No synchronized keyword
 - this.value = x;
 - }
 - }
 
不過,這個(gè)保證僅限于讀和寫,下面的代碼不是線程安全的:
- public void increment ()...{
 - // This is effectively two or three instructions:
 - // 1) Read current setting of ’value’.
 - // 2) Increment that setting.
 - // 3) Write the new setting back.
 - ++this.value;
 - }
 
在測試的時(shí)候,你可能不會(huì)捕獲到這個(gè)錯(cuò)誤。首先,測試與線程有關(guān)的錯(cuò)誤是很難的,而且很耗時(shí)間。其次,在有些機(jī)器上,這些代碼可能會(huì)被翻譯成一條指令,因此工作正常,只有當(dāng)在其它的虛擬機(jī)上測試的時(shí)候這個(gè)錯(cuò)誤才可能顯現(xiàn)。因此最好在開始的時(shí)候就正確地同步代碼:
- public synchronized void increment ()...{
 - ++this.value;
 - }
 
九、常見錯(cuò)誤9:在catch 塊中作清除工作
一段在catch塊中作清除工作的代碼如下所示:
- OutputStream os = null;
 - try...{
 - os = new OutputStream ();
 - // Do something with os here.
 - os.close();
 - }catch (Exception e)...{
 - if (os != null)
 - os.close();
 - }
 
盡管這段代碼在幾個(gè)方面都是有問題的,但是在測試中很容易漏掉這個(gè)錯(cuò)誤。下面列出了這段代碼所存在的三個(gè)問題:
1.語句os.close()在兩處出現(xiàn),多此一舉,而且會(huì)帶來維護(hù)方面的麻煩。
2.上面的代碼僅僅處理了Exception,而沒有涉及到Error。但是當(dāng)try塊運(yùn)行出現(xiàn)了Error,流也應(yīng)該被關(guān)閉。
3.close()可能會(huì)拋出異常。
上面代碼的一個(gè)更優(yōu)版本為:
- OutputStream os = null;
 - try...{
 - os = new OutputStream ();
 - // Do something with os here.
 - }finally...{
 - if (os != null)
 - os.close();
 - }
 
這個(gè)版本消除了上面所提到的兩個(gè)問題:代碼不再重復(fù),Error也可以被正確處理了。但是沒有好的方法來處理第三個(gè)問題,也許最好的方法是把close()語句單獨(dú)放在一個(gè)try/catch塊中。
十、常見錯(cuò)誤10: 增加不必要的catch 塊
一些開發(fā)者聽到try/catch塊這個(gè)名字后,就會(huì)想當(dāng)然的以為所有的try塊必須要有與之匹配的catch塊。
C++程序員尤其是會(huì)這樣想,因?yàn)樵贑++中不存在finally塊的概念,而且try塊存在的唯一理由只不過是為了與catch塊相配對。
增加不必要的catch塊的代碼就象下面的樣子,捕獲到的異常又立即被拋出:
- try...{
 - // Nifty code here
 - }catch(Exception e)...
 - {
 - throw e;
 - }finally...{
 - // Cleanup code here
 - }
 
不必要的catch塊被刪除后,上面的代碼就縮短為:
- try...{
 - // Nifty code here
 - }finally...{
 - // Cleanup code here
 - }
 
在本文中我為大家分享了十個(gè)常見的在Java開發(fā)中常見的易發(fā)的錯(cuò)誤,希望大家有了這方面的哈東東以后多多分享。
【編輯推薦】















 
 
 









 
 
 
 