Start learning free

LESSON 663 OF 671 · PROJECTS: OBJECT-ORIENTED

Stack in Java: Build MyStack on an ArrayList

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a private List<Integer> data = new ArrayList<>() and offers four operations.

The methods:

  • public void push(int value)
  • public int pop()
  • public int peek()
  • public int size()

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In Java, get on an empty list throws an IndexOutOfBoundsException.)

You start with: The starter already contains the code that uses your stack (below).

MyStack s = new MyStack();
s.push(10);
s.push(20);
s.push(30);
System.out.println("Top: " + s.peek());
System.out.println("Size: " + s.size());
System.out.println("Pop: " + s.pop());
System.out.println("Size: " + s.size());
System.out.println("Pop: " + s.pop());
System.out.println("Pop: " + s.pop());
System.out.println("Empty size: " + s.size());
s.push(7);
System.out.println("Top: " + s.peek());
System.out.println("Size: " + s.size());

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

ArrayList has add, get(index) and remove(index); the last index is data.size() - 1. pop must return the old top, so save it in a variable before calling remove, then return the variable.

class MyStack {
    private List<Integer> data = new ArrayList<>();

    public void push(int value) {
        data.add(value);
    }

    public int pop() {
        int top = data.get(data.size() - 1);
        data.remove(data.size() - 1);
        return top;
    }

    public int peek() {
        return data.get(data.size() - 1);
    }

    public int size() {
        return data.size();
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    JAVA · PROJECTS: OBJECT-ORIENTED

    Stack Impl in Java, explained

    Problem overview

    A stack is a pile where you only touch the top. The last value pushed is the first one popped (last in, first out). The task is to write a class MyStack that stores int values in a private List<Integer> data = new ArrayList<>() and has four methods:

    • push(int value) puts a value on top and returns nothing.
    • pop() removes the top value and returns it.
    • peek() returns the top value and leaves it in place.
    • size() returns how many values are stored.

    The tests never call pop or peek on an empty stack. The driver pushes 10, 20 and 30, peeks, pops all three values, pushes 7 and peeks again. The output shows last in, first out:

    Top: 30
    Size: 3
    Pop: 30
    Size: 2
    Pop: 20
    Pop: 10
    Empty size: 0
    Top: 7
    Size: 1
    

    Approach: the end of the list is the top

    An ArrayList is cheap to grow and shrink at its end, so the end of the list is the top of the stack. push appends. peek reads the last element, and pop reads it and then removes it. After pushing 10, 20 and 30, the list holds [10, 20, 30] and the top, 30, is at the last index, which is data.size() - 1.

    The one subtle point is pop, because it has two jobs: give the value back and take it off. Removing it first would lose the value, so the method saves it in a local variable, removes the element, and then returns the saved value.

    Step by step

    1. Declare the class MyStack. The driver's new MyStack() builds objects from it.
    2. Add the private field data, a List<Integer> that starts as an empty ArrayList. Only the stack's own methods touch it.
    3. Declare push as a public void method taking an int value.
    4. Append the value to the end with data.add(value).
    5. Declare pop as a public method returning int. Its body will have three lines.
    6. Save the top in an int named top, read with data.get at the last index.
    7. Remove the last item with data.remove and the same index.
    8. Return top, the value the caller asked for.
    9. Declare peek as a public method returning int.
    10. Return the last item of data without removing it.
    11. Declare size as a public method returning int.
    12. Return data.size(): one list item per stored value.

    The solution in Java

    class MyStack {
        private List<Integer> data = new ArrayList<>();
    
        public void push(int value) {
            data.add(value);
        }
    
        public int pop() {
            int top = data.get(data.size() - 1);
            data.remove(data.size() - 1);
            return top;
        }
    
        public int peek() {
            return data.get(data.size() - 1);
        }
    
        public int size() {
            return data.size();
        }
    }
    
    class Solution {
        public void mainFunction() {
            MyStack s = new MyStack();
            s.push(10);
            s.push(20);
            s.push(30);
            System.out.println("Top: " + s.peek());
            System.out.println("Size: " + s.size());
            System.out.println("Pop: " + s.pop());
            System.out.println("Size: " + s.size());
            System.out.println("Pop: " + s.pop());
            System.out.println("Pop: " + s.pop());
            System.out.println("Empty size: " + s.size());
            s.push(7);
            System.out.println("Top: " + s.peek());
            System.out.println("Size: " + s.size());
        }
    }
    

    Java details worth knowing:

    • Imports. List and ArrayList live in java.util. In a standalone Java file you add import java.util.*; at the top.
    • Boxing. The list holds Integer objects, while the methods use int. Java converts automatically: data.add(value) boxes the int, and int top = data.get(...) unboxes the Integer.
    • remove(int) against remove(Object). List has two remove methods, and with a List<Integer> the argument's type picks one. An int expression, like data.size() - 1, removes by position. For [10, 20, 30], data.remove(Integer.valueOf(10)) removes the value 10 and leaves [20, 30], while data.remove(1) on the resulting [20, 30] removes the item at position 1 and leaves [20]. In pop the argument is an index, which is what is needed.
    • Why pop saves first. After data.remove(...), the element is gone from the list. The local top keeps the value alive until the return.
    • The empty stack. data.get(data.size() - 1) on an empty list asks for index -1 and throws IndexOutOfBoundsException with the message Index -1 out of bounds for length 0. The lesson doesn't ask you to handle that case.

    Complexity

    Time: push appends in amortized O(1): the list occasionally grows its internal array, but averaged over many pushes each one costs a constant. peek, size and pop are O(1), because reading or removing the last element of an ArrayList shifts nothing.

    Space: O(n) for n stored values.

    Using the front of the list as the top would make push and pop O(n), because every other element would shift by one position.

    Tracing the driver

    The driver's output follows from the list: after the three pushes the list holds [10, 20, 30], so peek() prints 30 and size() prints 3. The first pop() prints 30 and leaves two items, then the next two pops print 20 and 10, so the size is 0. The stack is empty but still usable: push(7) makes it [7], so peek() prints 7 and size() prints 1.

    Edge cases and common mistakes

    • Returning before removing. A return data.get(...) line ends the method, so the remove below it never runs. The size would never shrink.
    • Removing without saving. If pop removes first and then reads the last index, it returns the wrong element, and on a one-element stack it fails.
    • Using the wrong index. With three values the top is at index 2, not 3. data.get(data.size()) throws.
    • Making the stack reusable. After popping everything, the stack has size 0 and accepts pushes again: after pushing 7, peek() returns 7 and size() returns 1.
    • Making data public. Outside code could then add or remove items in the middle, which a stack must not allow.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free