當前位置:才華齋>IT認證>JAVA認證>

Java程式設計常見問題彙總大綱

JAVA認證 閱讀(3.24W)

在我們寫Java程式的過程中,其實裡面有一些細節大家可能沒怎麼注意,雖然一般沒有什麼大問題,但俗話說的好,差之毫釐失之千里。所以我們一定要注意這些小細節。那在我們日常的程式設計中,有哪些我們不常注意的小細節呢?下面跟yjbys小編一起來看看吧!

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