开发者

Array of Generic Interface

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&l开发者_运维技巧t;T> s[] = new Sample<T>[2];// for this it shows error


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<Sameple> list = new ArrayList<Sameple>(); // this is OK and typesafe
    
  2. Create array without generics, put the code into special factory method annotated with @SuppressWarnings:

    public class Test {
        interface Sample<T>{}
        @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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜