[ACCEPTED]-Casting an array of Objects into an array of my intended class-object

Accepted answer
Score: 40

Because toArray() creates an array of Object, and 15 you can't make Object[] into DataObject[] just by casting it. toArray(DataObject[]) creates 14 an array of DataObject.

And yes, it is a shortcoming 13 of the Collections class and the way Generics 12 were shoehorned into Java. You'd expect 11 that Collection<E>.toArray() could return an array of E, but it 10 doesn't.

Interesting thing about the toArray(DataObject[]) call: you 9 don't have to make the "a" array 8 big enough, so you can call it with toArray(new DataObject[0]) if 7 you like.

Calling it like toArray(new DateObject[0]) is actually better 6 if you use .length later to get the array length. if 5 the initial length was large and the same 4 array object you passed was returned then 3 you may face NullPointerExceptions later

I asked a question earlier 2 about Java generics, and was pointed to 1 this FAQ that was very helpful: http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

Score: 3

To ensure type safety when casting an array 6 like you intended (DataObject[] dataArray = (DataObject[]) objectArray;), the JVM would have 5 to inspect every single object in the array, so 4 it's not actually a simple operation like 3 a type cast. I think that's why you have 2 to pass the array instance, which the toArray() operation 1 then fills.

Score: 2

After Java 8 with introduction of streams 3 and Lambda you can do the following too:

For 2 casting a normal Array of objects


For casting 1 a List


More Related questions