JAVA: How to create a generic Array
If you try to create a generic array in Java, you will notice that it will throw an error.
Coordinate[] coordinates = aClass.someMethod(Coordinate.class);
public
{
//Create an array to hold the data
int size=10;
T[] data = new
return data;
}
You will get the following error: “Cannot create a generic array of T”.
The way to get around that is to use the Array.newInstance(Class> componentType, int... dimensions)
public
{
//Create an array to hold the data
int size=10;
T[] data = (T[]) Array.newInstance(t, size);
return data;
}
Hope you find this handy little tip useful!
Tags: Java, Web Design and Development