4

Class A is of generic type and in class B i want to create an array of objects of type A with Integer as the generic parameter.

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

But in statement-1 i get a warning for unchecked conversion. What is the correct way of creating this array so i don't need to use any suppress warnings statement.

Rog Matthews
  • 2,949
  • 11
  • 34
  • 52

2 Answers2

1
@SuppressWarnings("unchecked")
A<Integer>[] arr = new A[3];
B(){
    for(int i=0;i<arr.length;i++)
     arr[i]=new A<Integer>();
}
Chandra Sekhar
  • 16,511
  • 14
  • 71
  • 109
1

Sometimes Java generics just doesn't let you do what you want to, and you need to effectively tell the compiler that what you're doing really will be legal at execution time.
So 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. Check this..

@SuppressWarnings("unchecked")
A<Integer>[] arr = new A[3];
B(){
   for(int i=0;i<arr.length;i++)
   arr[i]=new A<Integer>();
 }
Sumit Singh
  • 23,530
  • 8
  • 71
  • 99