0

This is my whole code, the problem requires me to use Array for solution.

import java.lang.reflect.Array;

public class MyStack<T> {
    public MyStack (Class<T[]> _class,int size){
        final T[] values = (T[]) Array.newInstance(_class,size);
        this.values = values;
        this.size=size;
    }

    private T[] values;
    private int top=0,size;

    public void push(T nextElement){
        if(isFull()){
            System.out.println("full");
        }
        else {
            values[top++] = nextElement;
        }
    }

    public T pop(){
        if(isEmpty()) {
            System.out.println("empty");
            return null;
        }
        else {
            return values[top--];
        }
    }

    public boolean isEmpty(){
        if (top==0)return true;
        return false;
    }

    public boolean isFull(){
        if(top==size-1)return true;
        else return false;
    }

    public static void main(String args[]){
        MyStack<Integer> myStack = new MyStack<Integer>(Integer[].class,9);
        for (int i =0;i<10;i++)
        {
            myStack.push(i);
        }
        while(!myStack.isEmpty()){
            System.out.println(myStack.pop());
        }
    }
}

When i compile it it throws Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer at values[top++] = nextElement; no matter which type i used from String, Integer or any other Objects. Is there a way to fix this problem ?

1 Answers1

1

You constructor takes a Class<T[]> but should take a Class<T>, also you don't need a variable shadow on values. I'd write it like

public MyStack(Class<T> _class, int size) { 
    this.values = (T[]) Array.newInstance(_class, size);
    this.size = size;
}

You don't need if else chains for isEmpty (just return the condition you are testing directly) - like

public boolean isEmpty() { 
    return top == 0;
}

Or for isFull

public boolean isFull() {
    return top == size - 1;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249