tags:

views:

55

answers:

1

Can we create array of generic interface in java?

interface Sample<T>{}

in other class

Sample<T> s[] = new Sample[2] ; // for this it shows warning

Sample<T> s[] = new Sample<T>[2];// for this it shows error
A: 

Unfortunately Java does not support creation of generic arrays. I do not know the exact reason. Actually generics exist at compile time only and are removed when you run javac, i.e. move from .java to .class. But it is not enough to understand the limitation. Probably they had some backwards compatibility problems with such feature.

Here are the workarounds you can use. 1. use collections (e.g. list) instead of array. List list = new ArrayList(); // this is OK and typesafe

  1. Create array without generics, put the code into special factory method annotated with @SuppressWarnings:

public class Test { interface Sample{}

@SuppressWarnings("unchecked")
public static <T> Sample<T>[] sampleArray() {
    return new Sample[2];
}

}

Now you can use this factory method without any additional warning.

General tip.

It is bad practice to suppress warnings. Warnings are potential problems. So if I have to suppress warning I at least try to decrease the scope where the warning is suppressed. Unfortunately legacy java APIs do not support generics. We often get warnings when we use such APIs. I am always trying to localize such uses into special classes or at least methods like sampelArray(). These methods are marked by @SuppressWarning and often contain comment that explain why warnings are suppressed here.

AlexR