ArrayList.toArray() 未转换为正确的类型?
所以,我得到的是:
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)
我怎样才能解决这个问题?
So, what I got is:
class BlahBlah
{
public BlahBlah()
{
things = new ArrayList<Thing>();
}
public Thing[] getThings()
{
return (Thing[]) things.toArray();
}
private ArrayList<Thing> things;
}
In the other class I got:
for (Thing thing : someInstanceOfBlahBlah.getThings())
{
// some irrelevant code
}
And the error is:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LsomePackage.Thing;
at somePackage.Blahblah.getThings(Blahblah.java:10)
How can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试:
您的原始版本不起作用的原因是
toArray()
返回Object[]
而不是Thing[]
。您需要使用另一种形式的 toArray --toArray(T[])
-- 获取Things
数组。Try:
The reason your original version doesn't work is that
toArray()
returnsObject[]
and notThing[]
. You need to use the other form oftoArray
--toArray(T[])
-- to get an array ofThings
.尝试
并
Try
and
有 2 个 toArray() 函数。
您正在使用第一个,它应该返回
Object[]
并且它正在这样做。如果您想获得正确的类型,请使用第二个版本:或者如果您不想在
new Thing[things.length]
上浪费更多空间,则只需将循环更改为强制转换:There are 2 toArray() functions.
You're using the first one, which is supposed to return
Object[]
and it's doing so. If you want to get correct type use the second version:or if you don't want to waste any more space on
new Thing[things.length]
then just change the loop to cast:尝试
列表。 toArray javadoc
try
List.toArray javadoc