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

Stack implementation with StackInterface

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

Problem

The code that I wrote is as follows:

public  class Astack implements StackInterface {
private int sz;
private Object[] a;
private int topPosition = -1;
public Astack(int sz){
   a = new Object[sz];
   this.sz = sz;
}
public int size(){
return topPosition+1;
}
public boolean isEmpty(){
  if(topPosition == -1){
  return true;
}
  return false;
}
public void push(Object element) throws StackFullException{
  if(topPosition+1 == sz){
    throw new StackFullException("Stack Full.");
  }
  a[++topPosition] = element;
}
public Object top() throws StackEmptyException{
  if(topPosition == -1){
    throw new StackEmptyException("Stack already Empty");
  }
return a[topPosition];
}
public Object pop() throws StackEmptyException{
  if(topPosition == -1){
    throw new StackEmptyException("Stack already Empty");
  }
  return a[topPosition--];
}
}


The StackInterface that I wrote:

public interface StackInterface{
    public int size();
    public boolean isEmpty();
    public Object top() throws StackEmptyException;
    public void push(Object element) throws StackFullException;
    public Object pop() throws StackEmptyException;
}

Solution

There isn't really much to optimize here, but there are definitely improvements you can make regarding usability and coding style.

  • use generics instead of Object, otherwise the stack is difficult to use in practice.



  • in practice, you would probably want a stack to increase its size automatically instead of throwing an exception.



  • your indentation is not consistent, making your code difficult to read.



  • you need more vertical whitespace, for example before a new method



  • your variable names could use improvement. What's a sz? What's an a? What's an Astack?

Context

StackExchange Code Review Q#139836, answer score: 7

Revisions (0)

No revisions yet.