1

I want to make an Universal stack using generics .

public class UniversalStack<E> implements StackInterface<E> {

    private E[] stack;
    private int dim;
    private int index;

    @SuppressWarnings("unused")
    public UniversalStack(int dim)
    {
        this.dim=dim;
        this.index=0;
        @SuppressWarnings("unchecked")
        E[] stack = (E[]) new Object[dim];


    }

    @Override
    public void push(E el) {
        // TODO Auto-generated method stub
        if(index+1<dim)
        {
            stack[index] = el;
            index=index+1;
        }

    }
}

Everything compiles succesfully . The problem comes when I call the following :

UniversalStack<Integer> integerStack = new UniversalStack<>(10);
integerStack.push(new Integer(1));

I get

Exception in thread "main" java.lang.NullPointerException
    at com.java.lab4.UniversalStack.push(UniversalStack.java:41)
    at com.java.lab4.testStack.main(testStack.java:14)

Could you explain me what am I doing wrong ? If I made a stupid mistake don't be harsh on me , I am a beginner so I don't really know much.

2 Answers 2

7

You're re-declaring stack within your constructor rather than assigning to the outer stack:

E[] stack = (E[]) new Object[dim];

Should be

stack = (E[]) new Object[dim];

therefore stack is null when used in push.

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

2 Comments

Yeah , that was it .. I didn't realize I re-declared the stack member until I read it again after I posted here . Thanks !
I think eclipse tried to warn you, but you added suppresswarnings annotation :-)
-1

Just use the stack class that already exists for Java.

Stack<Integer> stack = new Stack<Integer>();

More documentation is here http://docs.oracle.com/javase/6/docs/api/java/util/Stack.html

1 Comment

I'm confused, why does this warrant a -1? He's trying to use a stack, and I suggest he used the stack implementation that already exists? Seems like a better idea to use what exists and is tried and true than write your own....

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.