Another Stack implementation in Java

Posted on

Problem

I’m trying to write my own stack implementation using LinkedList. It looks like it is doing what it should doing. But how does it look from a design perspective?

If I will go for job interview and show such things to a interviewer, will they say: “that’s looks nice” or they rather will look at me with weird look asking “who let you in”?

import java.util.LinkedList;


public class Stack <T> {
private T t;
private LinkedList<T> stack;


public Stack() {
    this.stack = new LinkedList<>();
}

public void push(T t) {
    stack.add(t);
}

public boolean isEmpty(){
    if(stack.size()!=0){
        return false;
    } return true;
}

public T pop(){
    if(!isEmpty()) {
        return stack.removeLast();
    }
    return t;
}

public T peek(){
    if(!isEmpty()){
        return stack.getLast();
    }
    return t;
}

}

Solution

It looks like it is doing what it should be doing.

I don’t understand that remark. In particular, you posted no unit tests or other evidence of the target code being exercised in usual cases and in edge cases.

    private T t;

What is that? The ctor doesn’t affect it. It doesn’t appear to contribute to any Stack invariants. Why can’t pop() and peek() simply return null?

    if (stack.size() != 0) {
        return false;
    } return true;

Don’t show that at an interview. Use the more natural return stack.size() == 0 instead.

For some workloads involving a large stack, this implementation will show worse performance than one that uses a doubly linked list.

my addition to the very good answer of @J_H:

  1. Java LinkedList has a isEmpty() method. why is it better to use that than quering the size? because you might choose to replace LinkedList with another Collection implementation, one that implements isEmpty() differently.

  2. in the push() method I would prefer to call LinkedList‘s addLast() method since it saves the doubt where add() adds the new item.

Leave a Reply

Your email address will not be published. Required fields are marked *