當前位置:
首頁 > 最新 > Java常見問題匯總(一)

Java常見問題匯總(一)

每天在寫Java程序,其實裡面有一些細節大家可能沒怎麼注意,這不,有人總結了一個我們編程中常見的問題。雖然一般沒有什麼大問題,但是最好別這樣做。另外這裡提到的很多問題其實可以通過Findbugs( 網頁鏈接)來幫我們進行檢查出來。

字元串連接誤用

錯誤的寫法:

String s = ""; for (Person p : persons) { s += ", " + p.getName(); } s = s.substring(2); //remove first comma

正確的寫法:

StringBuilder sb = new StringBuilder(persons.size() * 16); // well estimated bufferfor (Person p : persons) { if (sb.length() > 0) sb.append(", "); sb.append(p.getName);}

錯誤的使用StringBuffer

錯誤的寫法:

StringBuffer sb = new StringBuffer(); sb.append("Name: "); sb.append(name +
); sb.append("!"); ... String s = sb.toString();

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

正確的寫法:

StringBuilder sb = new StringBuilder(100); sb.append("Name: "); sb.append(name); sb.append("
!"); String s = sb.toString();

或者這樣寫:

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

測試字元串相等性

錯誤的寫法:

if (name.compareTo("John") == 0) ... if (name == "John") ... if (name.equals("John")) ... if ("".equals(name)) ...

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

正確的寫法:

if ("John".equals(name)) ... if (name.length() == 0) ... if (name.isEmpty()) ...

數字轉換成字元串

錯誤的寫法:

"" + set.size() new Integer(set.size()).toString()

正確的寫法:

String.valueOf(set.size())

利用不可變對象(Immutable)

錯誤的寫法:

zero = new Integer(0); return Boolean.valueOf("true");

正確的寫法:

zero = Integer.valueOf(0); return Boolean.TRUE;

請使用XML解析器

錯誤的寫法:

int start = xml.indexOf("") + "".length(); int end = xml.indexOf(""); String name = xml.substring(start, end);

正確的寫法:

SAXBuilder builder = new SAXBuilder(false); Document doc = doc = builder.build(new StringReader(xml)); String name = doc.getRootElement().getChild("name").getText();

請使用JDom組裝XML

錯誤的寫法:

String name = ... String attribute = ... String xml = "" +""+ name +"" +"";

正確的寫法:

Element root = new Element("root"); root.setAttribute("att", attribute); root.setText(name); Document doc = new Documet(); doc.setRootElement(root); XmlOutputter out = new XmlOutputter(Format.getPrettyFormat()); String xml = out.outputString(root);

XML編碼陷阱

錯誤的寫法:

String xml = FileUtils.readTextFile("my.xml");

因為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 = string.getBytes();

這樣的代碼主要不具有跨平台可移植性。因為不同的平台可能使用的是不同的默認字元編碼。

正確的寫法:

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 = string.getBytes("ASCII");

未對數據流進行緩存

錯誤的寫法:

InputStream in = new FileInputStream(file); int b; while ((b = in.read()) != -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 = ... socket.connect(remote); InputStream in = socket.getInputStream(); int i = in.read();

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

正確的寫法:

Socket socket = ... socket.connect(remote, {}); // fail after 20s InputStream in = socket.getInputStream(); socket.setSoTimeout({}); int i = in.read();

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

頻繁使用計時器

錯誤代碼:

for (...) { long t = System.currentTimeMillis(); long t = System.nanoTime(); Date d = new Date(); Calendar c = new GregorianCalendar(); }

每次new一個Date或Calendar都會涉及一次本地調用來獲取當前時間(儘管這個本地調用相對其他本地方法調用要快)。

如果對時間不是特別敏感,這裡使用了clone方法來新建一個Date實例。這樣相對直接new要高效一些。

正確的寫法:

Date d = new Date(); for (E entity : entities) { entity.doSomething(); entity.setUpdated((Date) d.clone()); }

如果循環操作耗時較長(超過幾ms),那麼可以採用下面的方法,立即創建一個Timer,然後定期根據當前時間更新時間戳,在我的系統上比直接new一個時間對象快200倍:

private volatile long time; Timer timer = new Timer(true); try { time = System.currentTimeMillis(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { time = System.currentTimeMillis(); } }, 0L, 10L); // granularity 10ms for (E entity : entities) { entity.doSomething(); entity.setUpdated(new Date(time)); } } finally { timer.cancel(); }

捕獲所有的異常

錯誤的寫法:

Query q = ... Person p; try { p = (Person) q.getSingleResult(); } catch(Exception e) { p = null; }

這是EJB3的一個查詢操作,可能出現異常的原因是:結果不唯一;沒有結果;資料庫無法訪問,而捕獲所有的異常,設置為null將掩蓋各種異常情況。

正確的寫法:

Query q = ... Person p; try { p = (Person) q.getSingleResult(); } catch(NoResultException e) { p = null; }

忽略所有異常

錯誤的寫法:

try { doStuff(); } catch(Exception e) { log.fatal("Could not do stuff"); } doMoreStuff();

這個代碼有兩個問題, 一個是沒有告訴調用者, 系統調用出錯了. 第二個是日誌沒有出錯原因, 很難跟蹤定位問題。

正確的寫法:

try { doStuff(); } catch(Exception e) { throw new MyRuntimeException("Could not do stuff because: "+ e.getMessage, e);


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 java學習吧 的精彩文章:

Java新手問題匯總
java 基礎 語法
Java 面試 分享
JAVA基礎面試題 一
深入理解 Java的介面和抽象類

TAG:java學習吧 |