0

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);
        

    }
Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
ix.trc
  • 1
  • 1
    Does this answer your question? [How to create a generic array in Java?](https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) – Vala. D. Sep 07 '20 at 20:09
  • `` at runtime is erased to `Car` type which causes `(U[]) new Object[capacity]` to be compiled as `(Car[]) new Object[capacity]` which is causing the problem. Maybe instead of `CarListe` create list for all kind of objects like `Liste{...}` and later crate class with more *specific* content like `class CarListe extends Liste{ /*add constructors, etc*/}`. – Pshemo Sep 07 '20 at 20:23
  • I extended my CarList with my "normal" List (public class CarListe extends Liste) and it works. Thanks alot – ix.trc Sep 07 '20 at 20:49

0 Answers0