When using Java's for
each syntax, Stack
doesn't use LIFO ordering on the outputted elements. Consider the following code:
import java.util.Queue;
import java.util.Stack;
import java.util.LinkedList;
public class QueueStackTest {
private static int[] numbers = {1, 2, 3, 4, 5};
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
Queue<Integer> l = new LinkedList<Integer>();
for (int i : numbers) {
s.push(i);
l.offer(i);
}
System.out.println("Stack: ");
for(Integer i : s) {
System.out.println(i);
}
System.out.println();
System.out.println("Queue:");
for(Integer i : l) {
System.out.println(i);
}
}
}
Output:
Stack:
1
2
3
4
5
Queue:
1
2
3
4
5
Questions:
- Does this make sense? Is it a bug?
- Can I guarantee that this will, at least, return Queue elements in the correct order?
- When consuming (processing) a
Stack
or aQueue
, is this the best way to do it? Or should I make a more manual loop with something like:while(!s.isEmpty()) { handle(s.pop()); }
orwhile(!l.isEmpty()) { handle(l.poll()); }