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 <T> T[] someMethod(Class<T> t)
{
//Create an array to hold the data
int size=10;
T[] data = new <T>t[size];
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 <T> T[] someMethod(Class<T> t)
{

//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!

Edwin is the founder and editor of Little Handy Tips and Wollongong Fitness. He is also the developer for the Google Custom Search WordPress plugin and Custom About Author WordPress plugin. Find out more about him here.