I'm currently working on generics in Java. So far, I tried to rebuild an ArrayList class called "Liste" (in German) and then I tried to implement generics, so my list can hold different objects, but also provide type-safety.
In my implementation, a ClassCastException
is thrown when I try to cast my Object
array to an U
(in this case Car
) array. The only thing I don't understand, is the fact that the code compiles when I'm not giving the specific bound (U extends Car
). If I remove the bound, the code compiles and everything works fine.
public class CarListe<U extends Car> { // doesn't work with bound Car
private U[] array;
private int capacity;
public CarListe(int capacity) {
this.array = (U[]) new Object[capacity]; // the error ocurs in this line
}
}
Now the instantiation of a CarListe object
public static void main(String[] args) {
CarListe<Car> pkwCarListe = new CarListe<Car>(100);
}