Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Generic Interface

Tags:

java

generics

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
like image 262
Ravit Teja Avatar asked Aug 21 '26 05:08

Ravit Teja


1 Answers

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.

like image 147
AlexR Avatar answered Aug 22 '26 19:08

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!