How to create an array of type variables in Java?

In Java, you can declare an array of type variables, but I cannot create an array. It's impossible?

class ClassName<T> { { T[] localVar; // OK localVar = new T[3]; // Error: Cannot create a generic array of T } } 
+4
source share
5 answers

Generic array type does not exist in Java. You can use arraylist

Explanation:

an array in java has a covariant type.

Java arrays have the property that types are covariant, which means that a supertype reference array is a supertype of a subtype reference array. That is, Object[] is a supertype of String[] , for example. As a result of covariance, all type rules that are common for sub- and supertypes are applied: an array of subtypes can be assigned to a variable of a supertype array, arrays of subtypes can be passed as arguments to methods that expect arrays of supertypes, and so on and so forth. Here is an example:

 Object[] objArr = new String[10];// fine 

In contrast, general collections are not covariant. The instantiation of a parameterized type for a supertype is not considered an instance supertype of the same parameterized type for a subtype. That is, a LinkedList<Object> not a LinkedList<String> and, therefore, a LinkedList<String> cannot be used where a LinkedList<Object> ; there is no compatibility of assignments between these two instances of the same parameterized type, etc. Here is an example that illustrates the difference:

 LinkedList<Object> objLst = new LinkedList<String>(); // compile-time error 

Source: http://www.angelikalanger.com/Articles/Papers/JavaGenerics/ArraysInJavaGenerics.htm

+5
source
 T[] localVar = (T[])(new Vector<T>(3).toArray()); // new T[3]; 
+3
source

This is only possible in a language with reified generics like Gosu . Java has type erasure, so type T is not available at runtime.

+2
source

You can not. You can do this if you have a Class object representing T , you can use java.lang.reflect.Array :

 public static <T> T[] createArray(Class<T> clazz, int size) { T[] array = (T[]) java.lang.reflect.Array.newInstance(clazz, length); return array; } 
+1
source

Another way I got around is to create another class to hold the Variable variable, and then create an array of that class for example.

  public class test<T>{ data[] localVar = new data[1]; private class data<E>{ E info; public data(E e){ info = e; } } public void add(T e){ localVar[0] = new data<T>(e); } } 

the code above cannot be used for anything practical unless you want to add one element to the array, but it just shows the idea.

0
source

Source: https://habr.com/ru/post/1336183/


All Articles