2012-03-12 57 views
4

A類是泛型類型,而在B類中,我想創建一個Integer類型爲A的對象數組作爲泛型參數。在Java中創建通用數組

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

但是在聲明-1中,我得到了未經檢查的轉換的警告。什麼是創建這個陣列的正確方法,所以我不需要使用任何壓制警告聲明

+0

使用ArrayList .. – DarthVader 2012-03-12 06:26:01

+3

不能創建由於類型擦除通用陣列。 – blackcompe 2012-03-12 06:35:06

回答

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>(); 
} 
1
@SuppressWarnings("unchecked") 
A<Integer>[] arr = new A[3]; 
B(){ 
    for(int i=0;i<arr.length;i++) 
    arr[i]=new A<Integer>(); 
}