所以,我得到的是:
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)
我该如何解决这个问题?
答案 0 :(得分:8)
尝试:
public Thing[] getThings()
{
return things.toArray(new Thing[things.size()]);
}
原始版本不起作用的原因是toArray()
返回Object[]
而不是Thing[]
。您需要使用其他形式的toArray
- toArray(T[])
- 来获取Things
数组。
答案 1 :(得分:4)
尝试
private static final Thing[] NO_THING = {};
和
return (Thing[]) things.toArray(NO_THING);
答案 2 :(得分:0)
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
}
答案 3 :(得分:0)