指定foo
是完全沒用的,因爲這不會反映在調用方法中。
有實現相同的結果的幾種方法,但:
使用數組:
private void F1() {
boolean foo[] = new boolean[1];
List<String> result = F2(foo);
if(foo[0]) {
// do something
}
}
private List<String> F2(boolean[] foo) {
// Logic to set the result
List<String> result = new ArrayList();
if(condition) {
foo[0] = true;
}
return result;
}
或者可以保存值,而不改變其參考任何其他結構(AtomicBoolean
就是一個例子)。
改變你處理返回值的方式:
private void F1() {
List<String> result = F2();
if(result != null) {
// do something
}
}
private List<String> F2() {
// Logic to set the result
List<String> result = new ArrayList();
if(condition) {
return result;
}
return null;
}
返回null
其中一個Object
預期是一種常見的方式來表明,出事了,結果是不被認爲是有效的。不要誤以爲空的結果列表,這可能表明一切都很好,沒有什麼可以返回的。
拋出一個異常:
private void F1() {
try {
List<String> result = F2();
// do something
} catch (Exception e) {
e.printStackTrace();
}
}
private List<String> F2() {
// Logic to set the result
List<String> result = new ArrayList();
if(!condition) {
throw new Exception("Condition not met");
}
return result;
}
這可以是一個選中或未經檢查的異常,這取決於你想要的效果。例如,爲了表明輸入不正確,由於外部原因(I/O)導致一些錯誤,系統處於不允許該操作的狀態,所以還常用於...
爲什麼你需要擺脫警告嗎?聽起來像功課。 – Nicolas 2014-10-01 21:36:30
這怎麼可能是一項功課。這是爲了更好地理解java的做法。 – 2014-10-01 21:37:32