How to create array of generic type? How does generic Arrays.copyOf()
method work? It returns a copy of generic array. So it is possible to create generic arrays. But how? How one can write a method similar to copyOf()
?
Asked
Active
Viewed 732 times
2

Suzan Cioc
- 29,281
- 63
- 213
- 385
-
1Why not just look at the [source code of Arrays.copyOf()](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.copyOf%28java.lang.Object%5B%5D%2Cint%2Cjava.lang.Class%29)? – Philipp Reichart Jun 23 '12 at 22:50
-
1See also this question: http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation?rq=1 – DNA Jul 09 '12 at 22:34
2 Answers
6
If you need to create it at runtime you need at least know the type at that very moment, so you could use the following approach:
a = (T[]) Array.newInstance(c,s);
where T
is the generic type, c
is the class of T
and s
is the initial size.
Documentation here

Francisco Spaeth
- 23,493
- 7
- 67
- 106
-3
I am confused about what you're asking, but I'll try my best to answer.
If you want to create an array of generic type, the class containing the array will have to be parametrized with a generic. For example, this works:
class MyClass<T> {
T[] myGenericArray;
}
In most cases, I bet what you are doing can be achieved by an Object[] or something of that nature, although if you make your question more specific I may be able to offer more help.

Sam Stern
- 24,624
- 13
- 93
- 124
-
"this works" No, it doesn't. Read up on generics, type erasure and arrays in Java. – missingfaktor Jun 23 '12 at 22:54
-
1@missingfaktor: There is nothing wrong with the declaration given. It just does not answer the question (how to actually create an array). – user102008 Jun 30 '12 at 09:47