I am implementing a stack using queues. My pop() function originally looked like:
public void pop(){
queue1.isEmpty() ? queue2.poll() : queue1.poll();
}
This did not compile. What is wrong with this definition?
I am implementing a stack using queues. My pop() function originally looked like:
public void pop(){
queue1.isEmpty() ? queue2.poll() : queue1.poll();
}
This did not compile. What is wrong with this definition?
The conditional operator only works in an expression context. A statement is not an expression. In your case you need to use an if
statement:
public void pop(){
if (queue1.isEmpty()) {
queue2.poll();
} else {
queue1.poll();
}
}
If you are concerned about performance, then don't be. There is absolutely no performance penalty for using an if
statement.
You need to assign (or return) the
Object
you're polling. Something likeor (what I think you really want) - something like
See also JLS-15.25. Conditional Operator
? :
.