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:
Stack
or a Queue
, 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()); }
or while(!l.isEmpty()) { handle(l.poll()); }
Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.
The behavior of forEach() operation is explicitly non-deterministic. For parallel streams, forEach() operation does not guarantee to respect the encounter order of the Stream.
3) The enhanced for loop can only iterate in incremental order. we cannot configure it to go in decrement.
The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
There is an interesting footnote in Stack's Javadoc:
A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. For example:
Deque stack = new ArrayDeque();
An extended version of your program:
public static void main(String[] args) { Stack<Integer> s = new Stack<Integer>(); Deque<Integer> d = new ArrayDeque<Integer>(); Queue<Integer> l = new LinkedList<Integer>(); for (int i : numbers) { s.push(i); l.offer(i); d.push(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); } System.out.println(); System.out.println("Deque:"); for(Integer i : d) { System.out.println(i); } }
gives
.... Deque: 5 4 3 2 1
So maybe switch to Deque for a more consistent behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With