ArrayList.toArray()不能正确转换为指定类型?

3
所以,我的理解是:
class BlahBlah
{
    public BlahBlah()
    {
        things = new ArrayList<Thing>();
    }

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

    private ArrayList<Thing> things;
}

在另一个班级中,我学到了:

for (Thing thing : someInstanceOfBlahBlah.getThings())
{
    // some irrelevant code
}

错误信息为:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LsomePackage.Thing;
at somePackage.Blahblah.getThings(Blahblah.java:10)

我该如何解决这个问题?

我认为你不能这样做。或者说,我认为你不能转换Array对象,因为它是一个“Object[]”。但我相信你可以转换每个单独的数组元素。 - BenCole
4个回答

9

尝试:

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

你原本的代码无法运行是因为toArray()返回的是Object[]而不是Thing[]。你需要使用另一种形式的toArray-- toArray(T[]) --才能获得Things数组。

2
.size() 而不是 .length。否则 +1 - Bozho
参数不需要具有“正确”的大小,只需要类型信息即可。所以您可以使用 new Thing [0] 作为参数,或者更好的是使用Peter Lawrey的方法,使用静态常量final。 - MartinStettner
1
@MartinStettner 最好使用 things.toArray(new Thing[things.size()]);,请参考这个问题:https://dev59.com/j3VC5IYBdhLWcg3w0EsD - Eng.Fouad

4

尝试

private static final Thing[] NO_THING = {};

并且

return (Thing[]) things.toArray(NO_THING);

0

2个toArray()函数

    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.

你正在使用第一个版本,它应该返回Object[],并且确实如此。如果你想要获取正确的类型,请使用第二个版本:

things.toArray(new Thing[things.length]);

或者如果你不想在new Thing[things.length]上浪费更多的空间,那么只需将循环改为强制转换:

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

0

尝试

things.toArray(new Thing[0])

List.toArray javadoc

的意思是将“List.toArray javadoc”链接到页面上。该链接是与Java编程语言相关的,用于获取有关特定方法的文档和说明。在程序设计中,这种链接被广泛应用于易于访问和查找代码库中各种函数的文档。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接