This post will discuss 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, we cannot instantiate the array. 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 the Java Collections Framework wherever 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 the previous approach, 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]

That’s all about creating a generic array in Java.