Java編程常見問題彙總

學識都 人氣:2.57W

在我們寫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 + 'n');

nd("!");

...

String s = ring();

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

正確的寫法:

StringBuilder sb = new StringBuilder(100);

nd("Name: ");

nd(name);

nd("n!");

String s = ring();

或者這樣寫:

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

測試字符串相等性

錯誤的寫法:

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");