General

All other little handy tips that can’t really fit in any specific category

Photography

Photography technique, tutorials and equipment review.

Computers

Tips, tutorials and solutions for Windows, Macs, Linux, Servers and Media Centers. Get the very most out of your computer. Resources for all levels from newbies and techies.

Web Design and Development

Tools, tech tips and tutorials for web design and development. Including wordpress plugins and tweaks.

Tools and Productivity

Software, web applications, scripts and tools to make your computing, design, development or networking experience more easier, enjoyable and productive.

Home » Computers

JAVA: How to create a generic Array

Submitted by

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[] someMethod(Class t)
{
//Create an array to hold the data
int size=10;
T[] data = new 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[] someMethod(Class 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 Kwan 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. He also has a keen interest in Photography . Find out more about him here.

Google+ 

Tags: ,

css.php
%d bloggers like this: