天天看點

java 開發常見問題_Java程式設計常見問題彙總

Java程式設計常見問題彙總

本文介紹了Java程式設計中的一些常見問題彙總,本文總結的都是一些Java代碼中比較典型的錯誤,需要的朋友可以參考下

優先傳回空集合而非null

如果程式要傳回一個不包含任何值的集合,確定傳回的是空集合而不是null。這能節省大量的"if else"檢查。

public class getLocationName {

return (null==cityName ? "": cityName);

}

頻繁使用計時器

錯誤代碼:

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

}

重複包裝RuntimeException

錯誤的寫法:

try {

doStuff();

} catch(Exception e) {

throw new RuntimeException(e);

}

正确的寫法:

try {

doStuff();

} catch(RuntimeException e) {

throw e;

} catch(Exception e) {

throw new RuntimeException(e.getMessage(), e);

}

try {

doStuff();

} catch(IOException e) {

throw new RuntimeException(e.getMessage(), e);

} catch(NamingException e) {

throw new RuntimeException(e.getMessage(), e);

}

不正确的傳播異常

錯誤的寫法:

try {

} catch(ParseException e) {

throw new RuntimeException();

throw new RuntimeException(e.toString());

throw new RuntimeException(e.getMessage());

throw new RuntimeException(e);

}

主要是沒有正确的将内部的錯誤資訊傳遞給調用者. 第一個完全丢掉了内部錯誤資訊, 第二個錯誤資訊依賴toString方法, 如果沒有包含最終的嵌套錯誤資訊, 也會出現丢失, 而且可讀性差. 第三個稍微好一些, 第四個跟第二個一樣。

正确的寫法:

try {