Java 将对象数组转换为我想要的类的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/395030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting an array of Objects into an array of my intended class
提问by Daddy Warbox
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.
我不清楚使这种情况发生的铸造(或其他任何东西)的工作机制。
采纳答案by Paul Tomblin
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
.
由于toArray()
创建对象的数组,你不能让Object[]
成DataObject[]
铸造它而已。 toArray(DataObject[])
创建一个DataObject
.
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.
是的,这是 Collections 类和泛型被硬塞进 Java 的方式的一个缺点。您会期望它Collection<E>.toArray()
可以返回一个 E 数组,但事实并非如此。
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(DataObject[])
调用的有趣之处:您不必使“a”数组足够大,因此您可以根据需要调用它toArray(new DataObject[0])
。
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
toArray(new DateObject[0])
如果您.length
稍后使用它来获取数组长度,那么调用它实际上会更好。如果初始长度很大并且返回了您传递的相同数组对象,那么您NullPointerException
稍后可能会遇到s
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
我之前问过一个关于 Java 泛型的问题,有人指出这个 FAQ 很有帮助:http: //www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
回答by Henning
To ensure type safety when casting an array like you intended (DataObject[] dataArray = (DataObject[]) objectArray;
), the JVM would have to inspect every single object in the array, so it's not actually a simple operation like a type cast. I think that's why you have to pass the array instance, which the toArray()
operation then fills.
为确保在按预期 ( DataObject[] dataArray = (DataObject[]) objectArray;
)转换数组时类型安全,JVM 必须检查数组中的每个对象,因此它实际上不是像类型转换那样的简单操作。我认为这就是为什么你必须传递数组实例,toArray()
然后操作填充它。