Search⌘ K
AI Features

Generic Types

Explore how Java generics impact the creation and type safety of arrays, focusing on type erasure, covariance, and casting issues. Understand why direct generic array creation fails and how reflection provides a correct approach for creating generic arrays safely.

1.

Explain generic types?

Show Answer
Did you find this helpful?
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 ...