问题描述
仅供参考,有人可以快速解释一下是什么阻止了它的工作(在编译时):
Just for review, can someone quickly explain what prevents this from working (on compile):
private HashSet data;
...
public DataObject[] getDataObjects( )
{
return (DataObject[]) data.toArray();
}
...以及是什么使这种方式起作用:
...and what makes this the way that DOES work:
public DataObject[] getDataObjects( )
{
return (DataObject[]) data.toArray( new DataObject[ Data.size() ] );
}
我不清楚导致这种情况的强制转换(或其他任何机制)的机制.
I'm not clear on the mechanism at work with casting (or whatever it is) that makes this so.
推荐答案
因为 toArray()
创建了一个 Object 数组,而你不能使 Object[]
只需将其转换为 DataObject[]
即可.toArray(DataObject[])
创建一个 DataObject
数组.
Because toArray()
creates an array of Object, and you can't make Object[]
into DataObject[]
just by casting it. toArray(DataObject[])
creates an array of DataObject
.
是的,这是 Collections 类和泛型被硬塞进 Java 的方式的一个缺点.您可能希望 Collection.toArray()
可以返回一个 E 数组,但它不会.
And yes, it is a shortcoming of the Collections class and the way Generics were shoehorned into Java. You'd expect that Collection<E>.toArray()
could return an array of E, but it doesn't.
toArray(DataObject[])
调用的有趣之处:您不必使a"数组足够大,因此您可以使用 toArray(new DataObject[0])
如果你愿意.
Interesting thing about the toArray(DataObject[])
call: you don't have to make the "a" array big enough, so you can call it with toArray(new DataObject[0])
if you like.
像 toArray(new DateObject[0])
一样调用它实际上更好,如果您稍后使用 .length
来获取数组长度.如果初始长度很大并且返回了您传递的相同数组对象,那么您可能会在稍后遇到 NullPointerException
s
Calling it like toArray(new DateObject[0])
is actually better if you use .length
later to get the array length. if the initial length was large and the same array object you passed was returned then you may face NullPointerException
s later
我之前问过一个关于 Java 泛型的问题,有人指出这个 FAQ 很有帮助:http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
I asked a question earlier about Java generics, and was pointed to this FAQ that was very helpful: http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
这篇关于将对象数组转换为我想要的类的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!