0

Food.java

public class Food {
}

Animal.java

public class Animal<E> {
    private E[] a = (E[]) new Object[5];


    public E[] returnArray() {
        return a;
    }



    public static void main(String[] args) {
        Animal<Food> animal = new Animal<>();

        Object[] objs = animal.returnArray();
        Food[] fd = (Food[]) objs; // error happens here!
        fd[0] = new Food();


    }
}

error message

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ltestsample.Food; ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; [Ltestsample.Food; is in unnamed module of loader 'app')
    at testsample.Animal.main(Animal.java:19)

error happens when I try to convert the generic type array, Food[] fd = (Food[]) objs, it seems fd and obj are both Food[] array, what's going wrong here.

0 Answers0