Casting an array of Objects into an array of my intended class
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
.
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.
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.
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
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
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.