【问题标题】:Create Generic Array in Java [duplicate]在Java中创建通用数组[重复]
【发布时间】:2012-03-28 14:02:47
【问题描述】:
A 类是泛型类型,在 B 类中,我想创建一个 A 类型的对象数组,其中 Integer 作为泛型参数。
class A<T>
{}
class B
{
A<Integer>[] arr=new A[4]; //statement-1
B()
{
for(int i=0;i<arr.length;i++)
arr[i]=new A<Integer>();
}
}
但在 statement-1 中,我收到了未经检查的转换的警告。创建这个数组的正确方法是什么,所以我不需要使用任何抑制警告语句。
【问题讨论】:
标签:
java
arrays
oop
generics
【解决方案1】:
有时 Java 泛型并不能让你做你想做的事,你需要有效地告诉编译器你正在做的事情在执行时是合法的。
所以SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.
检查这个..
@SuppressWarnings("unchecked")
A<Integer>[] arr = new A[3];
B(){
for(int i=0;i<arr.length;i++)
arr[i]=new A<Integer>();
}
【解决方案2】:
@SuppressWarnings("unchecked")
A<Integer>[] arr = new A[3];
B(){
for(int i=0;i<arr.length;i++)
arr[i]=new A<Integer>();
}