2015-06-22 28 views
0

我正在使用隊列實現堆棧。我的流行()功能最初看起來像:使用三元運算符的無效java語法

public void pop(){ 
    queue1.isEmpty() ? queue2.poll() : queue1.poll(); 
} 

這沒有編譯。這個定義有什麼問題?

+0

您的queue1.isEmpty方法返回布爾值嗎? – sma

+1

'queue2.poll()'和'queue1.poll()'是否返回_same_類型? –

+0

@sma和Tim yes – quantum

回答

1

您需要指定(或返回)您正在輪詢的Object。喜歡的東西

public void pop(){ 
    Object obj = queue1.isEmpty() ? queue2.poll() : queue1.poll(); 
} 

或(我覺得你真的想) - 像也JLS-15.25. Conditional Operator ? :

public Object pop(){ 
    return queue1.isEmpty() ? queue2.poll() : queue1.poll(); 
} 

見。

1

條件運算符僅適用於表達式上下文。聲明不是表達式。你的情況,你需要使用一個if聲明:

public void pop(){ 
    if (queue1.isEmpty()) { 
     queue2.poll(); 
    } else { 
     queue1.poll(); 
    } 
} 

如果您關心性能,那麼就不一定了。使用if語句絕對沒有性能損失。