HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

How is my Java code for stack implementation?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stackjavaforhowcodeimplementation

Problem

The following example shows how to implement stack by creating user defined push() method for entering elements and pop() method for retrieving elements from the stack.

public class MyStack {
  private int maxSize;
  private long[] stackArray;
  private int top;

  public MyStack(int s) {
    maxSize = s;
    stackArray = new long[maxSize];
    top = -1;
  }

  public void push(long j) {
    stackArray[++top] = j;
  }

  public long pop() {
    return stackArray[top--];
  }

  public long peek() {
    return stackArray[top];
  }

  public boolean isEmpty() {
    return (top == -1);
  }

  public boolean isFull() {
    return (top == maxSize - 1);
  }

  public static void main(String[] args) {
    MyStack theStack = new MyStack(10);
    theStack.push(10);
    theStack.push(20);
    theStack.push(30);
    theStack.push(40);
    theStack.push(50);

    while (!theStack.isEmpty()) {
      long value = theStack.pop();
      System.out.print(value);
      System.out.print(" ");
    }

    System.out.println("");
  }
}

Solution

The stack that you have implemented (I guess for an assignment) is too limited because of the following:

  • It does not support generic types. Since every container class in Java can store any object, I would suggest you to incorporate that facility in your data structure as well.



  • It has only a limited storage capacity, due to the use of Java array. It would be better to use a container class that can grow dynamically, such as an ArrayList, LinkedList or a Vector.



  • You should properly handle the boundary condition of popping from an empty stack.



  • Try to test your main function with a real-life application, such as evaluating a post-fix expression or checking valid parenthesization etc.

Context

StackExchange Code Review Q#54187, answer score: 5

Revisions (0)

No revisions yet.