【问题标题】:Exception in thread "main" java.lang.ArrayStoreException when store object into array将对象存储到数组中时,线程“main”java.lang.ArrayStoreException 中的异常
【发布时间】:2017-08-10 13:21:54
【问题描述】:

这是我的全部代码,问题需要我用数组来解决。

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());
        }
    }
}

当我编译它时,它会抛出 Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer at values[top++] = nextElement; 无论我使用 String、Integer 还是任何其他类型对象。 有没有办法解决这个问题?

【问题讨论】:

    标签: java arrays object


    【解决方案1】:

    您的构造函数采用Class&lt;T[]&gt;,但应该采用Class&lt;T&gt;,而且您不需要values 上的变量阴影。我会这样写

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

    isEmpty 不需要 if else 链(只需直接返回您正在测试的条件) - 就像

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

    isFull

    public boolean isFull() {
        return top == size - 1;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多