m********7 发帖数: 1368 | 1 JAVA刚入门,请教一个低级的问题,如何 create a generic array? 如果比较复杂,
能否提供一个好用的reference,多谢!
public static > void sort(T[] a){
T[] tmp = new T[a.length]; <---error
sort(a,tmp, 0, a.length-1);
} | d****i 发帖数: 4809 | 2 You need to use the following to create a generic array. Java's generics has
type erasure, so you can't create generic array at compile-time since it
needs runtime info.
public static > void sort(T[] a, Class clazz) {
T[] tmp = (T[]) Array.newInstance(clazz, a.length);
}
Or you can just use ArrayList directly without the hassle.
【在 m********7 的大作中提到】 : JAVA刚入门,请教一个低级的问题,如何 create a generic array? 如果比较复杂, : 能否提供一个好用的reference,多谢! : public static > void sort(T[] a){ : T[] tmp = new T[a.length]; <---error : sort(a,tmp, 0, a.length-1); : }
| m********7 发帖数: 1368 | 3 type erasure! 这下大概明白为啥总报错了,谢谢热心的帮助! 哈!
has
【在 d****i 的大作中提到】 : You need to use the following to create a generic array. Java's generics has : type erasure, so you can't create generic array at compile-time since it : needs runtime info. : public static > void sort(T[] a, Class clazz) { : T[] tmp = (T[]) Array.newInstance(clazz, a.length); : } : Or you can just use ArrayList directly without the hassle.
| f*******n 发帖数: 12623 | 4 为什么sort会需要创造一个新的array?你调用的另外的这个sort用这个array干嘛?给
它一个Object[]不行吗?
Java的array在运行时知道自己的元素类型,所以不同类型的array在运行时是不同的。
但是好像T这些类型参数在运行时不存在。
反正你调用的另外的这个sort也不会知道你给它的东西是不是T[],你可以创造一个
Object[]给它,假装是T[]:
Object[] tmp = new Object[a.length];
sort(a,(T[])tmp, 0, a.length-1);
但是最好是另外的这个sort根本就接受Object[];反正对它不会有区别。
如果你真的想创造正确类型的array,你可以从你运行时已经有的T[]那里得出元素类型
,跟着用那个来创造新的array。这样不需要分开再传递一个类型。
Class clazz = (Class)a.getClass().getComponentType();
T[] tmp = Array.newInstance(clazz, a.length);
sort(a,tmp, 0, a.length-1);
【在 m********7 的大作中提到】 : JAVA刚入门,请教一个低级的问题,如何 create a generic array? 如果比较复杂, : 能否提供一个好用的reference,多谢! : public static > void sort(T[] a){ : T[] tmp = new T[a.length]; <---error : sort(a,tmp, 0, a.length-1); : }
| F****n 发帖数: 3271 | 5 @SuppressWarnings("unchecked")
T[] tmp = (T[])Array.newInstance(a.getClass().getComponentType(), a.length);
【在 m********7 的大作中提到】 : JAVA刚入门,请教一个低级的问题,如何 create a generic array? 如果比较复杂, : 能否提供一个好用的reference,多谢! : public static > void sort(T[] a){ : T[] tmp = new T[a.length]; <---error : sort(a,tmp, 0, a.length-1); : }
|
|