Generic Arrays

Java-Generic Arrays

Generic Arrays

It’s also possible to create generic arrays. There are two important generics restrictions that apply to arrays. First, you cannot instantiate an array whose element type is a type parameter. Second, you cannot create an array of type-specific generic references. Following class shows, it’s valid to declare a reference to an array of type T, T tarray[ ]:

Generic Arrays

But, you cannot instantiate an array of T as:

Generic Arrays

The reason you can’t create an array of T is that there is no way for the compiler to know what type of array to actually create. However, you can pass a reference to a type-compatible array to Gen( ) when an object is created and assign that reference to tarray, as tarray = arr. This works because the array passed to Gen has a known type, which will be the same type as T at the time of object creation. You can’t declare an array of references to a specific generic type. The following line will not compile :

Generic Arrays

You can create an array of references to a generic type if you use a wildcard<?>, however, as :

Generic Arrays
Program

Generic Arrays

Program Source

class Gen<T> {

    T tarray[];

    Gen(T arr[]) {
        tarray = arr;
    }

    T getSpecifiedItem(int i) {
        return tarray[i];
    }
}

public class Javaapp {

    public static void main(String[] args) {

        Gen<Integer> gen1 = new Gen<Integer>(new Integer[]{10, 20, 30, 40, 50});
        System.out.println("Integer : " + gen1.getSpecifiedItem(3));

        Gen<String> gen2 = new Gen<String>(new String[]{"AB", "CD", "EF", "GH"});
        System.out.println("String  : " + gen2.getSpecifiedItem(3));

        Gen<?> gen3[] = new Gen<?>[5];

        gen3[0] = new Gen<Integer>(new Integer[]{10, 20, 30, 40, 50});

        gen3[1] = new Gen<Float>(new Float[]{1.1f, 2.2f, 3.3f, 4.4f, 5.5f});
    }
}

Leave a Comment