Generic Types
Explore how Java generic types interact with arrays, including type erasure implications and covariance rules. Learn why generic arrays cause class cast exceptions and how to safely create them using reflection for type safety.
We'll cover the following...
We'll cover the following...
1.
Explain generic types?
Show Answer
Did you find this helpful?
1.
What are generic methods?
Show Answer
1 / 4
The above code fails because on line 5 there is an implicit cast from Object[] to String[]. Let's look at the erasure of the method to better understand the outcome. The rules of erasure tell us to replace the unbounded parameter T with Object.
Erasure of createArray method
Object[] createArray(int size) {
Object[] array = (Object[]) new Object[size];
return array;
}
...