0
我正在使用隊列實現堆棧。我的流行()功能最初看起來像:使用三元運算符的無效java語法
public void pop(){
queue1.isEmpty() ? queue2.poll() : queue1.poll();
}
這沒有編譯。這個定義有什麼問題?
我正在使用隊列實現堆棧。我的流行()功能最初看起來像:使用三元運算符的無效java語法
public void pop(){
queue1.isEmpty() ? queue2.poll() : queue1.poll();
}
這沒有編譯。這個定義有什麼問題?
您需要指定(或返回)您正在輪詢的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();
}
見。
條件運算符僅適用於表達式上下文。聲明不是表達式。你的情況,你需要使用一個if
聲明:
public void pop(){
if (queue1.isEmpty()) {
queue2.poll();
} else {
queue1.poll();
}
}
如果您關心性能,那麼就不一定了。使用if
語句絕對沒有性能損失。
您的queue1.isEmpty方法返回布爾值嗎? – sma
'queue2.poll()'和'queue1.poll()'是否返回_same_類型? –
@sma和Tim yes – quantum