Search⌘ K
AI Features

Generic Types

Explore how Java generics interact with arrays, focusing on type erasure and covariance issues that cause class cast exceptions. Understand the correct approach to create generic arrays using reflection to ensure type safety and avoid runtime errors.

1.

Explain generic types?

Show Answer
1 / 3
Java
class Demonstration {
public static void main( String args[] ) {
(new Printer<Integer>()).print(Integer.valueOf(555));
(new Printer<String>()).print("print away");
(new Printer<Object>()).print(new Demonstration());
}
}
class Printer<T> {
void print(T t) {
System.out.println("printing : " + t.toString());
}
}
1.

What are generic methods?

Show Answer
1 / 4
Java
class Demonstration {
public static void main( String args[] ) {
// Attempt to create a generic array
// results in a ClassCastException
String[] array = Demonstration.<String>createArray(5);
}
static <T> T[] createArray(int size) {
T[] array = (T[]) new Object[size];
return array;
}
}

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;
    }
...