Question 19
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> legacy = new Stack<>();
Deque<Integer> modern = new ArrayDeque<>();
for (int i = 1; i <= 3; i++) { legacy.push(i); modern.push(i); }
System.out.println(legacy + " " + modern + " " + legacy.peek() + " " + modern.peek());
}
}
- A [3, 2, 1] [3, 2, 1] 3 3
- B [1, 2, 3] [1, 2, 3] 3 1
- C [1, 2, 3] [3, 2, 1] 3 3 Correct
- D [3, 2, 1] [1, 2, 3] 3 3
Correct Answer: Option C
Stack extends Vector and pushes at the end of the vector, so it prints bottom to top; ArrayDeque pushes at the head and prints top to bottom. Both peek at 3.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!