This post is a continuation to the previous posts on Array Reification. Today I would like to discuss about different ways to convert a collection to an array.
The collections framework contains two utilitarian methods.
The first method converts the concrete collection instance to an Object array whereas the second one converts the collection instance to the reified type (runtime type) of the array instance provided as a parameter to it.
In this example, we tried to mimic the actual behavior in our own utility method. In this method, we first check whether the length of the array provided as argument is smaller than the size of the actual collection instance. If so, we use reflection to create another instance of the reified type of the array with the same size of the collection.
Finally, we just need to insert the elements of the collection to the array.
This example is similar to the previous one but the difference lies in the array creation. In the previous example, the user needs to provide an array instance to the method but in this method, we need user to provide the reified type of the actual array. I basically prefer this example as this example is less noisy and more user-friendly. If you are not aware of the Class<T> syntax, it is a representation of a class at runtime. In Java 5, this class Class has been rendered generic Class<T>.
As an example, String.class has a type of Class<String>.
Unchecked Cast Warning
If you have tried running the aforementioned custom examples, you would encounter Unchecked Cast Warning message which occurs due to the cast from a non-qualified type to a generic type.