java USES generic parameter types to construct array details and instances

  • 2020-06-07 04:34:13
  • OfStack

java USES generic parameter types to construct array details and instances


I was typing code a while ago when a question occurred to me. What if we want to create an array in a method that takes one argument? In the case of typology, this is not difficult. What if we pass in a parameter of a generic type?

public static <T> T[] creArray (T obj){
    T[] arr = new T[10];

Using T to direct the new array as shown above is an error, resulting in an error of 1: Cannot create a generic array of T. There is no support in Java for creating arrays directly for unknown types.

Finally, I got such a perfect solution:

package Test;

import java.lang.reflect.Array;

 * @author QuinnNorris
 *  Creates an array of generic types in the generic method 
public class Test {
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    String a = "ccc";// create 1 a String , as a generic type 
    String[] ar = creArray(a);
    for(String art :ar)// Loop to print 

  // Generic static methods 
  public static <T> T[] creArray (T obj){
    T[] arr = (T[])Array.newInstance(obj.getClass(), 5);
    arr[1] = obj;
    return arr;

The code output is as follows:

ccc // Output in a method arr[1] 
null // The following 5 One is main The value of the array iterated out by the loop  

The above method is completely feasible, and we construct arrays of specified types by using the newInstance method of the Array class. It should also make sense to use reflection to do this. Since the generic type T can only be determined when it is run in, the way we can create a generic array must also be done at the java runtime. The technique that works at the java runtime is reflection.

In addition, see null, just here to sort out the values initialized by different types of arrays in java:

Basic type (numeric) : 0
Basic type (Boolean) : false
Basic type (char type) :(char) 0
Object type: null

Thank you for reading, I hope to help you, thank you for your support to this site!

Related articles: