2012-03-12 13 views
4

クラスAはジェネリック型であり、クラスBではジェネリックパラメータとしてInteger型のオブジェクト型の配列を作成したいと考えています。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

+3

あなたは消去を入力するため、汎用的な配列を作成することはできません。 – blackcompe

答えて

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>(); 
} 
関連する問題