CJCoding With Joseph
15per day
← Back to Question List
Java Code Walkthrough #40

Generic Stack Push and Pop

mediumGenerics, Classes

📄 Code

Read carefully — what does this print?
1import java.util.ArrayList;
2 
3class Stack<T> {
4 private ArrayList<T> items = new ArrayList<>();
5 
6 public void push(T item) {
7 items.add(item);
8 }
9 
10 public T pop() {
11 return items.remove(items.size() - 1);
12 }
13 
14 public int size() {
15 return items.size();
16 }
17}
18 
19public class Main {
20 public static void main(String[] args) {
21 Stack<String> stack = new Stack<>();
22 stack.push("a");
23 stack.push("b");
24 stack.push("c");
25 System.out.println(stack.pop());
26 System.out.println(stack.size());
27 }
28}

🎯 Your Answer