Java Generics: What Beginners Find Surprising by Agnieszka Kozubek, 31 January 2013 Java generics
Surprise 1: I can't create an object of parameter type!
It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what
Read full article from Java Generics: What Beginners Find Surprising | OneWebSQL
Backwards compatibility
In case of Java generics, binary compatibility means that the JVM knows NOTHING about type parameters. The code has two versions: the source code version with type parameters, and the bytecode version where type parameters are erased. The bytecode looks very much like Java 4 version of the code.Surprise 1: I can't create an object of parameter type!
return
new
T();
First, the type parameter T is only present at compile-time. In bytecode it is replaced by itsbound, Motorcycle. So the runtime type of new T() is Motorcycle. The compile-time type of new T() is T. In a concrete instance of MotorcycleFactory the type T might be a concrete type, like Kawasaki.
Another reason is that you can't guarantee that type T has a no-argument public constructor. In Java there is no way to specify this requirement.
Surprise 2: I can't create an array of objects of parameter type
public
T[] vehicles =
new
T[
10
];
The code does not compile. The error message says Cannot create a generic array of T.
A Java array remembers the type of its elements. So an array of type T should know type T. But there is no type T at runtime!
If the above code was correct, the type T[] would be erased to its bound type, Vehicle[]. However, elsewhere in the code we could have:
1
2
| Garage<Car> carGarage = new Garage<Car>(); Car[] cars = carGarage.vehicles; |
This code would compile without errors. At runtime carGarage.vehicles would be of typeVehicle[]. We would have a runtime error: carGarage.vehicles type does not match the type of variable cars
It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what
T
is at runtime, you can't create the array.Read full article from Java Generics: What Beginners Find Surprising | OneWebSQL