How to use array type generics in Java?

In Java, I want to create a function that accepts any type of content list and then returns an array of the same type I have so far

public static <T>[] listToArray(List<T> items) {
    <T>[] names = new <T>[items.size()];
    for(int i=0; i<items.size(); i+=1) {
        names[i] = items.get(i);
    }
    return names;
}

But there are many grammatical errors

Who knows how to do this?

thank you

Solution

Effective Java from Bloch, item 25:

explain:

Array is covariant, which means that if the class dog extends the class animal, you can do this:

Animal[] animals = new Animal[5];
animals[0] = new Dog();

The same does not apply to generics because generics are invariant:

List<Animal> animals = new LinkedList<Animal>();
animals.add(new Dog()); // compilation error!!!

Array implementation means that all information about array types is available at run time and compile time Similarly, generics are erased, which means that type information exists only during compilation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>