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()
?
如何创建泛型数组?泛型array . copyof()方法是如何工作的?它返回一个泛型数组的副本。所以创建通用数组是可能的。但如何?如何编写类似copyOf()的方法?
2 个解决方案
#1
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.
其中T是泛型类型,c是T的类,s是初始大小。
Documentation here
文件在这里
#2
-2
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.
在大多数情况下,我打赌你所做的事情可以通过一个物体或类似的东西来实现,尽管如果你把你的问题说得更具体一些,我可能会提供更多的帮助。
#1
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.
其中T是泛型类型,c是T的类,s是初始大小。
Documentation here
文件在这里
#2
-2
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.
在大多数情况下,我打赌你所做的事情可以通过一个物体或类似的东西来实现,尽管如果你把你的问题说得更具体一些,我可能会提供更多的帮助。