2

How can i create a generic array in java, the right way?

T[] buffer = (T[]) new Object[maxSize];

Would it better to create a new generic collection and then cast it?

Fabian
  • 578
  • 2
  • 7
  • 19

3 Answers3

1

Just declare a generic list:

List<T> list = new ArrayList<T>();

Or check answer here

0

Somthing like this

final T[] a = (T[]) Array.newInstance(clazz, size);
Ashwel
  • 994
  • 8
  • 16
0

You can use newInstance method that offer Array class, but it require the Class of type.

The only solution that i see is create a Object array and then cast it to T[]

T[] array = (T[])Array.newInstance(Object.class, size); 
David Geirola
  • 576
  • 2
  • 15