clueless_b
clueless_b

Reputation: 9

How would writing methods for a non-generic stack class work?

I'm a little confused on how classes, constructors, and stacks work. I'm trying to create an array with a default size of 5. Then, I have to set the array size by using a constructor. Then, I have to write methods to push and pop values in the array. This is what I have so far

public class createStack{

    double [] array = new double[5];

    private int top = 0;

    public createStack(double[] array){

        this.array = array;

    }
    public void push(double[] array){
        if(top >= array.length){
            System.out.println("Stack is full");

        }

        top++;

    }
}

Am I doing this correctly? Also, how would I write methods for push and pop? I understand how the methods work, but I'm really confused on where to go with them.

Upvotes: 0

Views: 76

Answers (1)

David Conrad
David Conrad

Reputation: 16419

There are a number of problems here:

  • Classes are named with noun phrases, not verb phrases.
  • Class names conventionally begin with a capital letter. E.g., DoubleStack not createStack.
  • It doesn't make sense to have an initializer for the field but also assign the field based on a value passed to the constructor. The value passed to the constructor is always going to supersede the initializer.
  • The semantics of top are unclear. Does it point to the current top of the stack, or the next slot that will be used? It sounds like the former, but since the stack starts out empty, top = 0 can't point to the current top, so it appears to be the latter.
  • It doesn't make any sense for push to take an array as a parameter. It should take the single double value to push onto the stack.
  • Also, push doesn't do anything with the backing array in the field, it only looks at the array that was passed to it.

Here's an example of something more like I would expect to see:

public class DoubleStack {
    private double[] array;
    private int top = -1; // top points to the current top of the stack, if any

    public DoubleStack() {
        array = new double[5];
        // note: this could be done with an initializer and this constructor could be omitted
    }

    public void push(double value) {
        if (top >= array.length - 1) {
            throw new IllegalStateException("Stack Overflow");
        }
        ++top;
        array[top] = value;
        // note: the previous two lines could be combined; keeping it simple
    }

    public double pop() {
        if (top < 0) {
            throw new NoSuchElementException("Stack Empty");
        }
        double value = array[top];
        --top;
        return value;
    }
}

Possible changes would be to have a constructor that took a size as a parameter and created an array of the desired size instead of the default of 5; or using an ArrayList<Double> as a backing store for the stack so that the size would not be fixed.

Upvotes: 1

Related Questions