English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Detailed explanation and instance of constructing an array with generic parameter types in java
Preface:
The other day while coding, I suddenly thought of a question. Usually, our arrays are passed as parameters to methods. How do we create an array within a method? It's not difficult when the type is clear. What if the parameter is a generic type parameter?
public static <T> T[] creArray (T obj){ T[] arr = new T[10]; }
It is incorrect to use T to directly create an array as shown above, which will result in a compile-time error: Cannot create a generic array of T. Java does not support the direct creation of arrays with unknown types.
Finally, I got such a perfect solution:
package Test; import java.lang.reflect.Array; /** * * @author QuinnNorris * Create an array of generic types in generic methods */ public class Test { public static void main(String[] args) { // TODO Auto-generated method stub String a = "ccc";//Create a String as a generic type String[] ar = creArray(a); for(String art :ar)//Loop printing System.out.println(art); } //Generic static method public static <T> T[] creArray (T obj){ T[] arr = (T[])Array.newInstance(obj.getClass(), 5); arr[1] = obj; System.out.println(arr[1]); return arr; } }
The code output is as follows:
ccc //Output in the method arr[1] null //Below5This is the array value iterated out in the main loop ccc null null null
The above method is completely feasible. We constructed an array of a specified type by using the newInstance method of the Array class. It is reasonable to use reflection to complete this task. Because the generic type T can only be determined at runtime, we can also create generic arrays by finding ways at runtime in Java, and the technology that can take effect at runtime in Java is reflection.
By the way, seeing null here, let's sort out the initialization values of different types of arrays in Java here as well:
Basic type (numeric type): 0
Basic type (boolean type): false
Basic type (char type): (char) 0
Object type: null
Thank you for reading, I hope it can help everyone, thank you for your support to our website!