Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...