Create a generic array in Java
When using generics, I think plenty of people tried the following code, to create a generic array
T[] array = new T[];
When we write code compiler will report Cannot create a generic array of T
, beginner when generics, see this mistake to think that Java can not create a generic array, with the continuous in-depth, when Tinking in Java generics see, Java is possible to create generic, really ignorant to limit their imagination.
Java, create a generic example:
Create a generic array of key classes
import java.lang.reflect.Array;
class GenericsArray {
@SuppressWarnings({ "unchecked", "hiding" })
public static <T> T[] getArray(Class<T> componentType,int length) {
return (T[]) Array.newInstance(componentType, length);
}
}
Test category
import java.util.Arrays;
public class TestGenericArray {
public static void main(String[] args) {
@SuppressWarnings("static-access")
Person[] persons = new GenericsArray().getArray(Person.class, 10);
System.out.println(Arrays.toString(persons));
for (int i = 0; i < persons.length; i++) {
persons[i]=new Person(i);
}
System.out.println(Arrays.toString(persons));
}
}
Person class
public class Person {
private int id;
public Person(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person [id=" + id + "]";
}
}
Test Results