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

Array Implementation of Stack

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

Problem

I've implemented the basic logic of a stack data structure. How can I make this code more generic? Is there any better way to display the stack contents?

StackMethods.java

import java.util.Arrays;

public class StackMethods {
    private int top;
    int size;
    int[] stack ;

    public StackMethods(int arraySize){
        size=arraySize;
        stack= new int[size];
        top=-1;
    }

    public void push(int value){
        if(top==size-1){
            System.out.println("Stack is full, can't push a value");
        }
        else{

            top=top+1;
            stack[top]=value;
        }
    }

    public void pop(){
        if(!isEmpty())
            top=top-1;
        else{
            System.out.println("Can't pop...stack is empty");
        }
    }

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

    public void display(){

        for(int i=0;i<=top;i++){
            System.out.print(stack[i]+ " ");
        }
        System.out.println();
    }
}


StackReviseDemo.java

public class StackReviseDemo {

    public static void main(String[] args) {
        StackMethods newStack = new StackMethods(5);
        newStack.push(10);
        newStack.push(1);
        newStack.push(50);
        newStack.push(20);
        newStack.push(90);

        newStack.display();
        newStack.pop();
        newStack.pop();
        newStack.pop();
        newStack.pop();
        newStack.display();
    }
}

Solution

Good

  • Naming of parameters and methods follow the naming convention



Bad

  • not checking input parameter for constructor



  • not listening to previous answers ( pop() returning nothing )



  • not using braces {} for every if..else statement



Additional

  • int size should be final as it won't be changed.



  • Instead of display() you can override toString() as this is more common.



  • Instead of writing to System.out you should throw an exception.



  • give your variables some space to breathe. E.g top=top+1; would be more readable if written like so top = top + 1;

Context

StackExchange Code Review Q#64139, answer score: 9

Revisions (0)

No revisions yet.