Java ArrayList.toArray()未转换为正确的类型?

Java ArrayList.toArray()未转换为正确的类型?,java,arraylist,Java,Arraylist,所以,我得到的是: class BlahBlah { public BlahBlah() { things = new ArrayList<Thing>(); } public Thing[] getThings() { return (Thing[]) things.toArray(); } private ArrayList<Thing> things; } 错误是: Exc

所以,我得到的是:

class BlahBlah
{
    public BlahBlah()
    {
        things = new ArrayList<Thing>();
    }

    public Thing[] getThings()
    {
        return (Thing[]) things.toArray();
    }

    private ArrayList<Thing> things;
}
错误是:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LsomePackage.Thing;
at somePackage.Blahblah.getThings(Blahblah.java:10)
如何解决此问题?

请尝试:

public Thing[] getThings()
{
    return things.toArray(new Thing[things.size()]);
}
原始版本无法工作的原因是返回的是
Object[]
,而不是
Thing[]
。您需要使用另一种形式的
toArray
--来获取
事物的数组

试试看

private static final Thing[] NO_THING = {};

或者,如果您不想在
新事物[things.length]
上浪费更多空间,只需将循环更改为cast:

Thing thing = null;
for (Object o : someInstanceOfBlahBlah.getThings())
{
    thing = (Thing) o;
    // some unrelevant code
}
试一试


我想你做不到。或者更确切地说,我认为不能强制转换数组对象,因为它是一个
对象[]
。但我相信您可以强制转换每个单独的数组元素。
.size()
而不是
.length
。否则+1参数不需要有“正确”的大小,它只需要用于类型信息iirc。因此,您可以使用
新事物[0]
作为参数,或者更好地使用Peter Lawrey的方法和静态最终常数。@MartinStettner最好使用
things.toArray(新事物[things.size()),看到这个问题:@Eng Fouad谢谢,我不知道。
return (Thing[]) things.toArray(NO_THING);
    Object[] toArray()
        Returns an array containing all of the elements in this list in the correct order.
    <T> T[] toArray(T[] a)
        Returns an array containing all of the elements in this list in the correct order;
        the runtime type of the returned array is that of the specified array.
things.toArray(new Thing[things.length]);
Thing thing = null;
for (Object o : someInstanceOfBlahBlah.getThings())
{
    thing = (Thing) o;
    // some unrelevant code
}
things.toArray(new Thing[0])