2014-10-01 50 views
1

我有以下兩個函數,其中,我需要在第二個函數中設置布爾值,但我需要稍後在調用函數中使用該值。將值傳遞給調用者而不使用`return`

限制:

  1. 我不能在第二個函數返回boolean值。
  2. 由於線程安全,我不能將其用作全局變量。

什麼是最有效和最乾淨的方式來實現這一目標?

private void F1() 
{ 
    boolean foo = false; 
    List<String> result = F2(foo); 

    if(foo) 
    { 
     // do something 
    } 
} 

private List<String> F2(boolean foo) 
{ 
// Logic to set the result 
    List<String> result = new ArrayList(); 

    if(condition) 
    { 
     foo = true; 
    } 

    return result; 
} 
+0

爲什麼你需要擺脫警告嗎?聽起來像功課。 – Nicolas 2014-10-01 21:36:30

+0

這怎麼可能是一項功課。這是爲了更好地理解java的做法。 – 2014-10-01 21:37:32

回答

3

你可以使用一個可變包裝各地boolean模擬傳遞通過引用。 AtomicBoolean可以重新用於此目的。你不會將它用於原子性,只是在一個函數中設置它的值並在另一個函數中讀取它的能力。

private void F1() 
{ 
    AtomicBoolean foo = new AtomicBoolean(false); 
    List<String> result = F2(foo); 

    if(foo.get()) 
    { 
     // do something 
    } 
} 

private List<String> F2(AtomicBoolean foo) 
{ 
// Logic to set the result 
    List<String> result = new ArrayList(); 

    if(condition) 
    { 
     foo.set(true); 
    } 

    return result; 
} 

另一個常見的,但即使是kludgier,做到這一點的方式是1元素的數組。

boolean[] foo = new boolean[] {false}; 

同樣的技巧適用。 F2會做

foo[0] = true; 

這是很醜陋,但你會看到它不時,因爲哎,有時候你得做你必須做的事情。

1

指定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)導致一些錯誤,系統處於不允許該操作的狀態,所以還常用於...

相關問題