简体   繁体   English

如何创建泛型类型的数组?

[英]How to create array of generic type?

How to create array of generic type? 如何创建泛型类型的数组? How does generic Arrays.copyOf() method work? 通用Arrays.copyOf()方法如何工作? 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() ? 如何编写类似于copyOf()

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是通用类型, cT的类, s是初始大小。

Documentation here 这里的文件

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. 在大多数情况下,我敢打赌,您可以通过Object []或类似性质的东西来实现您的工作,尽管如果您使问题更具体,我可能会提供更多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM