Java: Stack Implementation vs. Groovy Stack (pop()-, push()-Methods)

Java-Logo

Relating to my article from here i want to show an example, how you can implement a Stack in Java and how much lines of code you’ll have to write therefor:

First we create an Interface called Stack.
There we define our methods we want to have in our Stack Api

package stack.interfaces;

public interface Stack {

	public abstract void push(Object t);
	public abstract Object pop();
	public abstract Integer size();
	public abstract void clear();
}

Next, let’s create a Stack Implementation, where we implement the methods of our Interface

package stack.implementation;

import stack.interfaces.Stack;

public class StackImpl implements Stack {

	private Object[] stack;
	private int max;
	private int current;

	public StackImpl(final int sizeOfStack) {
		max = sizeOfStack - 1;
		stack = new Object[max];
		current = 0;
	}

	@Override
	public void push(Object t) {
		if (current <= max) {
			stack[current++] = t;
		}
	}

	@Override
	public Object pop() {
		return (current > 0 ? stack[--current] : null);
	}

	@Override
	public Integer size() {
		return current;
	}

	@Override
	public void clear() {
		stack = new Object[max];
		System.out.println("Stack was cleared successful");
	}

}

And last but not least, let’s try our Java Stack in a DemoApp

package stack.implementation;

import java.math.BigDecimal;
import java.math.BigInteger;

import stack.interfaces.Stack;

public class StackDemo {

	public static void main(String[] args) {
		
		Stack stack = new StackImpl(10);
		stack.push("Patrick");
		stack.push(10);
		stack.push(new BigDecimal(BigInteger.valueOf(1000000)));
		stack.push(47.13);
		
		// size should be 4
		System.out.println(stack.size());
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		// now we get null, because all elements removed from stack
		System.out.println(stack.pop());
		// size should be 0
		System.out.println(stack.size());
	}
}

Now compare this Stack Implementation to the related article with the Groovy methods pop() and push(), which where added by the GDK to our Java Collections… But it depends on how your companies philisophie is in using newer / scripting languages instead of the old stack, if you can simplify your life by using for example Groovy.