为什么在这种情况下为“线程“主”中的异常java.lang.ClassCastException”?

时间:2019-01-14 16:59:50

标签: java

主方法中的

base.buffer.length抛出异常,而isFull方法有效,有人可以帮我了解发生了什么事吗?

package chp14;

public class BaseBoundedBuffer<V> {
    private final V[] buffer;
    private int head, tail, count;

    public BaseBoundedBuffer(int capacity) {
        this.buffer = (V[]) new Object[capacity];
    }

    public boolean isFull() {
        return buffer.length == count; // But this works
    }

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

    public static void main(String[] args) {
        BaseBoundedBuffer<String> base = new BaseBoundedBuffer<>(10);
        System.out.println(base.isFull());
        int count = base.buffer.length;
        // This line throws an exception, but the method isFull works, why?
        // Exception in thread "main" java.lang.ClassCastException:
        //      java.base/[Ljava.lang.Object; cannot be cast to java.base/[Ljava.lang.String;
        //          at chp14.BaseBoundedBuffer.main(BaseBoundedBuffer.java:21)

    }
}

0 个答案:

没有答案