當前位置:才華齋>計算機>java語言>

Java程式設計常見問題

java語言 閱讀(3.28W)

在我們日常的程式設計中,有哪些我們不常注意的小細節呢?下面內容由小編為大家介紹Java程式設計常見問題,供大家參考!

Java程式設計常見問題

字串連線誤用

錯誤的寫法:

String s = "";

for (Person p : persons) {

s += ", " + ame();

}

s = tring(2); //remove first comma

正確的寫法:

StringBuilder sb = new StringBuilder(() * 16); // well estimated buffer

for (Person p : persons) {

if (th() > 0) nd(", ");

nd(ame);

}

錯誤的使用StringBuffer

錯誤的寫法:

StringBuffer sb = new StringBuffer();

nd("Name: ");

nd(name + '');

nd("!");

...

String s = ring();

問題在第三行,append char比String效能要好,另外就是初始化StringBuffer沒有指定size,導致中間append時可能重新調整內部陣列大小。如果是JDK1.5最好用StringBuilder取代StringBuffer,除非有執行緒安全的要求。還有一種方式就是可以直接連線字串。缺點就是無法初始化時指定長度。

正確的寫法:

StringBuilder sb = new StringBuilder(100);

nd("Name: ");

nd(name);

nd("!");

String s = ring();

或者這樣寫:

String s = "Name: " + name + "!";

測試字串相等性

錯誤的寫法:

if (areTo("John") == 0) ...

if (name == "John") ...

if (ls("John")) ...

if (""ls(name)) ...

上面的程式碼沒有錯,但是不夠好。compareTo不夠簡潔,==原義是比較兩個物件是否一樣。另外比較字元是否為空,最好判斷它的長度。

正確的寫法:

if ("John"ls(name)) ...

if (th() == 0) ...

if (pty()) ...

數字轉換成字串

錯誤的寫法:

"" + ()

new Integer(())ring()

正確的寫法:

eOf(())

利用不可變物件(Immutable)

錯誤的寫法:

zero = new Integer(0);

return eOf("true");

正確的寫法:

zero = eOf(0);

return ;

請使用XML解析

錯誤的寫法:

int start = xOf("") + ""th();

int end = xOf("");

String name = tring(start, end);

正確的寫法:

SAXBuilder builder = new SAXBuilder(false);

Document doc = doc = d(new StringReader(xml));

String name = ootElement()hild("name")ext();

請使用JDom組裝XML

錯誤的寫法:

String name = ...

String attribute = ...

String xml = ""

+""+ name +""

+"";

正確的寫法:

Element root = new Element("root");

ttribute("att", attribute);

ext(name);

Document doc = new Documet();

ootElement(root);

XmlOutputter out = new XmlOutputter(rettyFormat());

String xml = utString(root);

XML編碼陷阱

錯誤的寫法:

String xml = TextFile("");

因為xml的編碼在檔案中指定的,而在讀檔案的時候必須指定編碼。另外一個問題不能一次就將一個xml檔案用String儲存,這樣對記憶體會造成不必要的浪費,正確的做法用InputStream來邊讀取邊處理。為了解決編碼的問題, 最好使用XML解析器來處理。

未指定字元編碼

錯誤的寫法:

Reader r = new FileReader(file);

Writer w = new FileWriter(file);

Reader r = new InputStreamReader(inputStream);

Writer w = new OutputStreamWriter(outputStream);

String s = new String(byteArray); // byteArray is a byte[]

byte[] a = ytes();

這樣的程式碼主要不具有跨平臺可移植性。因為不同的平臺可能使用的是不同的'預設字元編碼。

正確的寫法:

Reader r = new InputStreamReader(new FileInputStream(file), "ISO-8859-1");

Writer w = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-1");

Reader r = new InputStreamReader(inputStream, "UTF-8");

Writer w = new OutputStreamWriter(outputStream, "UTF-8");

String s = new String(byteArray, "ASCII");

byte[] a = ytes("ASCII");

未對資料流進行快取

錯誤的寫法:

InputStream in = new FileInputStream(file);

int b;

while ((b = ()) != -1) {

...

}

上面的程式碼是一個byte一個byte的讀取,導致頻繁的本地JNI檔案系統訪問,非常低效,因為呼叫本地方法是非常耗時的。最好用BufferedInputStream包裝一下。曾經做過一個測試,從/dev/zero下讀取1MB,大概花了1s,而用BufferedInputStream包裝之後只需要60ms,效能提高了94%! 這個也適用於output stream操作以及socket操作。

正確的寫法:

InputStream in = new BufferedInputStream(new FileInputStream(file));

無限使用heap記憶體

錯誤的寫法:

byte[] pdf = toPdf(file);

這裡有一個前提,就是檔案大小不能講JVM的heap撐爆。否則就等著OOM吧,尤其是在高併發的服務器端程式碼。最好的做法是採用Stream的方式邊讀取邊儲存(本地檔案或database)。

正確的寫法:

File pdf = toPdf(file);

另外,對於伺服器端程式碼來說,為了系統的安全,至少需要對檔案的大小進行限制。

不指定超時時間

錯誤的程式碼:

Socket socket = ...

ect(remote);

InputStream in = nputStream();

int i = ();

這種情況在工作中已經碰到不止一次了。個人經驗一般超時不要超過20s。這裡有一個問題,connect可以指定超時時間,但是read無法指定超時時間。但是可以設定阻塞(block)時間。

正確的寫法:

Socket socket = ...

ect(remote, 20000); // fail after 20s

InputStream in = nputStream();

oTimeout(15000);

int i = ();

另外,檔案的讀取(FileInputStream, FileChannel, FileDescriptor, File)沒法指定超時時間, 而且IO操作均涉及到本地方法呼叫, 這個更操作了JVM的控制範圍,在分散式檔案系統中,對IO的操作內部實際上是網路呼叫。一般情況下操作60s的操作都可以認為已經超時了。為了解決這些問題,一般採用快取和非同步/訊息佇列處理。