使用toArray()方法的ClassCastException

时间:2016-09-21 21:06:06

标签: java

我正在为toArray方法编写junit测试,这是ArrayBasedStack的方法之一。这个类里面有一个数组,toArray方法复制元素并返回。该方法由类提供,我试图打印出数组中的每个元素。

此方法复制本地数组并返回具有Object类型的复制数组。

public T[] toArray() {
    T[] copy = (T[]) new Object[this.size()];
    for (int i = 0; i < this.size(); i++) {
        copy[i] = (T) this.myArray[i];
    }

    return copy;
}

对于测试,我设置了String数组,如下所示:

private ArrayBasedStack stack;

public void setUp(){
    stack = new ArrayBasedStack<String>();
}

为了测试toArray()方法,我尝试了:

   public void testToArray(){
        stack.push("000");
        stack.push("111");
        assertEquals(2, stack.toArray().length);
        assertEquals("111", stack.toArray()[0]);
    }

除了toArray()方法,其他方法&#39;测试顺利通过,例如:peek()push()clear()equals()等等。

但是,只有此测试才会返回assertEquals

的错误
    assertEquals(2, stack.toArray().length);
    assertEquals("111", stack.toArray()[0]);

错误是:

>java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
        at arraystack.ArrayBasedStackTest.testToArray(ArrayBasedStackTest.java:82)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298)
        at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
        at java.util.concurrent.FutureTask.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

1 个答案:

答案 0 :(得分:2)

    T[] copy = (T[]) new Object[this.size()];

在这里,你对编译器撒谎。它不是T[],除非T[]Object[]

编写此方法的正确方法与Collections执行此方法的方式相同,方法是提供一个原型,如果您幸运的话已经是正确的大小:

import java.lang.ref.Array;

public T[] toArray(T[] a)
{
    if (a.length != this.size())
    {
        a = Array.newInstance(a.getClass().getComponentType(), this.size());
    }
    for (int i = 0; i < this.size(); i++)
    {
        a[i] = (T) this.myArray[i];
    }
    return a;
}

或者:

import java.util.Arrays;

public T[] toArray(T[] a)
{
    return Arrays.copyOf(this.myArray, this size());
}