search
HomeJavajavaTutorialjava—Constructing an array with generic parameter types


I suddenly thought of a question when I was coding a while ago. Usually our array is passed into the method as a parameter. What if we want to create an array in the method? When the type is clear, this is not difficult. What if the parameters we pass in are parameters of a generic type?

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

The above method of using T to create a new array directly is wrong, and an error will appear during compilation: Cannot create a generic array of T.. Java does not support directly creating arrays of unknown types.

Finally I got such a perfect solution:

package Test;import java.lang.reflect.Array;/**
 * 
 * @author QuinnNorris
 * 在泛型方法中创建泛型类型的数组
 */public class Test {
    public static void main(String[] args) {        // TODO Auto-generated method stub

        String a = "ccc";//创建一个String,作为泛型类型
        String[] ar = creArray(a);        for(String art :ar)//循环打印
            System.out.println(art);
    }    //泛型静态方法
    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    //方法中输出的arr[1] 

  null    //以下5个是main中循环迭代出的数组值 

  ccc 

  null 

  null 

  null


The above method is completely feasible. We construct an array of a specifiable type by using the newInstance method of the Array class. It should also make sense to use reflection to do this job. Because the generic type T can only be determined at runtime, we must find a way to create a generic array at Java runtime. The only technology that works at Java runtime is reflection.

I also saw null, so I would like to sort out the values ​​of different types of array initialization in Java:

  1. Basic type (numeric type): 0

  2. Basic type (boolean): false

  3. Basic type (char type): (char) 0

  4. Object type: null

I suddenly thought of a problem when I was coding a while ago. Usually our array is passed into the method as a parameter. What if we want to create an array in the method? When the type is clear, this is not difficult. What if the parameters we pass in are parameters of a generic type?

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

The above method of using T to directly create a new array is wrong, and an error will appear during compilation: Cannot create a generic array of T.. Java does not support directly creating arrays of unknown types.

Finally I got such a perfect solution:

package Test;import java.lang.reflect.Array;/**
 * 
 * @author QuinnNorris
 * 在泛型方法中创建泛型类型的数组
 */public class Test {
    public static void main(String[] args) {        // TODO Auto-generated method stub

        String a = "ccc";//创建一个String,作为泛型类型
        String[] ar = creArray(a);        for(String art :ar)//循环打印
            System.out.println(art);
    }    //泛型静态方法
    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    //方法中输出的arr[1] 

  null    //以下5个是main中循环迭代出的数组值 

  ccc 

  null 

  null 

  null


The above method is completely feasible. We construct an array of a specifiable type by using the newInstance method of the Array class. It should also make sense to use reflection to do this job. Because the generic type T can only be determined at runtime, we must find a way to create a generic array at Java runtime. The only technology that can work at Java runtime is reflection.

I also saw null, so I would like to sort out the values ​​of different types of array initialization in Java:

  1. Basic type (numeric type): 0

  2. Basic type (boolean): false

  3. Basic type (char type): (char) 0

  4. Object type: nul

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.