Teo
Teo

Reputation: 3442

Java generics NullPointerException

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.

Upvotes: 1

Views: 1141

Answers (2)

dsingleton
dsingleton

Reputation: 1006

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

Upvotes: -1

James Montagne
James Montagne

Reputation: 78690

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.

Upvotes: 7

Related Questions