有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我想使用泛型生成数组

我想用generices生成数组
但出现了编译错误
如何使用泛型生成数组

public class Test {

    public static void main(String[] args) {
        String[] datas = Test.changeToArray("apple");
        for (String data : datas) {
            System.out.println(data);
        }
        Boolean[] bools = Test.changeToArray(true);
        for (Boolean bool : bools) {
            System.out.println(bool);
        }
    
    }

    public static <T> T[] changeToArray(T data) {
        // i want this..
        // but this is compile error
        // Cannot create a generic array of T
        T[] datas = new T[] {data};
        return datas;
    }

}

共 (1) 个答案

  1. # 1 楼答案

    请通读泛型的restrictions。不允许在java中创建参数化类型的数组。见java docs