无法在类中实例化通用数据类型 [英] Cannot instantiate generic data type in class
问题描述
我有一个不可变的类,具有以下布局:
public final class A< T> {
private ArrayList< T>我的列表;
private A(){
myList = new ArrayList< T>();
}
public A< T> addData(T t){
newOb = //创建一个新列表并使用重载的构造函数实例化
T newT = new T(); ***********错误*************
newOb.myList.add(newT);
返回newOb;
}
.........
}
我在这里得到的错误是不能实例化类型T
。现在,我认为这与Java中的 type erasure
有关。
我该如何克服这个问题?我想将传递给addData的参数的新副本添加到我的列表中。
在java语言中,泛型是通过擦除来实现的,所以不可能实例化泛型。也不可能灌输一个泛型类型的数组等。
我该如何克服这个问题?我想将传递给addData的参数
的新副本添加到列表中。使用Cloneable
接口作为绑定的类型或添加您自己的类似接口。I have an immutable class , with the following layout ,
public final class A <T> { private ArrayList<T> myList; private A(){ myList = new ArrayList<T>(); } public A<T> addData(T t){ A newOb = // make a new list and instantiate using overloaded constructor T newT = new T(); ***********ERROR HERE************* newOb.myList.add(newT); return newOb; } ......... }
The error that I get here is
cannot instantiate type T
. Now , I think this is related to maybetype erasure
in Java.How can I overcome this ? I want to add a new copy of the argument that is being passed to addData into my list.
解决方案In java language generics are implemented by erasure, so it is impossible to instantiate a generic type. Also it is impossible to instiate an array of generic type and so on.
How can I overcome this ? I want to add a new copy of the argument that is being passed to addData into my list.
You can try to use
Cloneable
interface as a type bound or add your own similar interface.这篇关于无法在类中实例化通用数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!