1

I'm working on a project where I have to push String values into a stack. Whenever I push the first value into the stack it goes in with no problem, but after that any element I push turns into 'null'. Here's some of my sample code

public void push (E element){

    if( isEmpty() ){
        stack = (E[]) new Object[1];
        stack[0] = element;
    } else {

        int size = stack.length + 1;
        E[] tmpStack = (E[]) new Object[size];

        for (int i = 0; i < stack.length - 1; i++ ) {

        tmpStack[i] = stack[i];
        }

        stack = tmpStack;

        tmpStack = null;

        stack[size - 1] = element;
        }

Here's how I've been calling the method:

String elementArray[] = str.split(",");

    for(int i = 0; i < elementArray.length; i++){
        stack.push(elementArray[i]);
    }    

1 Answer 1

2

You have an off-by-one error. You're not copying the last element out of your source stack.

This:

for (int i = 0; i < stack.length - 1; i++ ) {

should be:

for (int i = 0; i < stack.length; i++ ) {

Bonus tip: Consider using System.arraycopy.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.