如何创建泛型类型的数组? [英] How to create array of generic type?

查看:104
本文介绍了如何创建泛型类型的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建泛型类型的数组?如何通用 Arrays.copyOf()法的工作?它返回通用数组的一个副本。所以有可能创建通用阵列。但是如何?如何可以写类似于 copyOf()

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()?

推荐答案

如果您需要在运行时你至少需要知道在那一刻类型,创建它,所以你可以用下面的办法:

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);

其中, T 是泛型类型, C 是类的牛逼取值是初始大小。

where T is the generic type, c is the class of T and s is the initial size.

文件<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Array.html#newInstance%28java.lang.Class,%20int%29\">here

这篇关于如何创建泛型类型的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆