【问题标题】:why cant I create an array attribute as a type parameter in java [duplicate]为什么我不能在java中创建一个数组属性作为类型参数[重复]
【发布时间】:2020-04-20 03:42:24
【问题描述】:

我想创建一个这样的数组:

public class Population<T> {
    T[] a = new T[10];
}

但是,编译器向我抛出了这个错误:

Type parameter 'T' cannot be instantiated directly

为什么会发生这种情况,我可以做些什么来克服这个问题?

【问题讨论】:

  • 使用列表代替

标签: java class types type-parameter


【解决方案1】:

正如编译器所提到的,您不能直接执行此操作。给出适合您情况的答案并不简单,因为没有实施细节。

一种可能性是通过构造函数注入数组/列表/集合。

public class Population<T> {
    private final List<T> members; 
    public Population(List<T> members) {
        this.members = members;
    }
}

然后使用变成

List<Animal> animals = new ArrayList<Animal>();
Population<Animal> population = new Population(animals);

【讨论】:

    猜你喜欢
    • 2016-06-20
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多