0

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?

quantum
  • 99
  • 1
  • 6
  • Does your queue1.isEmpty method return a Boolean? – sma Jun 22 '15 at 01:16
  • 1
    Does `queue2.poll()` and `queue1.poll()` return the _same_ type? – Tim Biegeleisen Jun 22 '15 at 01:18
  • What Throwable (Exception or Error) did compilation produce? In case you are implementing an ArrayDeque it has a pop method that would need overriding -- and it is a natural fit for stack implementation. –  Jun 22 '15 at 01:26
  • Although this use of the ternary operator is illegal in Java, interestingly it is legal in C/C++. (Not to say that it's good or bad.) – Nayuki Jun 22 '15 at 02:40

2 Answers2

1

You need to assign (or return) the Object you're polling. Something like

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

or (what I think you really want) - something like

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

See also JLS-15.25. Conditional Operator ? :.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285