Creating a Generic Array in Java

In this post, we will see how to create a generic array in Java using an Object Array and Reflection Array class.


 

Arrays in Java contains information about their component type for allocating memory during runtime. Now if the component type is not known at runtime, the array cannot be instantiated. Consider,

E[] arr = new E[capacity];

This uses Generics. We know that Generics are not present in the byte code generated by the compiler because of type erasure in Java. That means the Type information is erased at the runtime and new E[capacity] won’t know what type needs to be instantiated. To avoid this behavior, we should use List provided by Java Collections Framework whereever we need generics.

 
But there are ways to create a generic array-like data structure in Java which are covered below:

 

1. Using Object Array

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]
[A, B, C, D, E]

 

2. Using Reflection

We can use the Reflection Array class to create an array of a generic type known only at runtime. Please note that unlike previous approach, here we’re explicitly passing the Type information to the class constructor, which is further being passed to the Array.newInstance().

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]
[A, B, C, D, E]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz