How to implement Stack in Java. Simple solution. – IT Blog
IT Blog
Boris IT Expert

How to implement Stack in Java. Simple solution.

Boris~November 24, 2020 /Stack

How to implement a stack data structure in Java? First of all, you should understand the main idea of the stack. Try to imagine an empty box for books. And you can put only one book at once. If you put another book, it will go on top of the previous one. What will you do if you need to get the first book out? It would be best if you took out the books that lay on top of it first. If the first book was “Lord Of The Rings”, the second was “Harry Potter,” and the third is “King-Kong”. You should take out “King-Kong” first, then “Harry Potter” and only after that “Lord Of the Rings”. That is how the stack data structure works. The stack is a linear data structure.

A simple example of stack implementation? The step-by-step solution in Java.

If you want to implement the stack data structure, you should understand the next steps: 

interface Stack<T> {
    void push(T item);
    T pop();
    boolean isEmpty();
    int size();
}
add elements in stack java

Full code of the stack class:

 class SimpleStack<T> implements Stack<T> {

        private ArrayList<T> arrayList = new ArrayList<>();

        @Override
        public void push(T item) {
            //In Stack need to add on first index
            arrayList.add(0, item); 
        }

        @Override
        public T pop() {
         //In Stack need to remove first index item
            return arrayList.remove(0); 
        }

        @Override
        public boolean isEmpty() {
        //Checking if stack is empty
           return arrayList.isEmpty(); 
        }

        @Override
        public int size() {
        //Checking the size of the stack
           return arrayList.size(); 
        }
    }
 private void addOne() {
        simpleStack.push(1);
        for (int i = 0; i < simpleStack.size(); i++){
            Log.d("test", "-> " + i);
        }
    }
 private void removeOne() {
        simpleStack.pop();
        for (int i = 0; i < simpleStack.size(); i++){
            Log.d("test", "-> " + i);
        }
    }
private void testStack() {

        //Fill stack with numbers from 1 to 10
        for (int i=0; i < 9; i++){
            simpleStack.push(i); //Adding elements
            Log.d("test", "adding -> " + i);
        }

        Log.d("test", "Size: " + simpleStack.size());
        Log.d("test", "------------------------------");

        //Removing elements from the stack
        while (!simpleStack.isEmpty()){
            Log.d("test", "removed -> " + simpleStack.pop());//Removing element from stack
        }

    }

In this article, you figured out how to implement a stack in Java. 

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!