泛型的集合“无法实例化ArrayList类型”?扩展OpDTO> " [英] Collections of generics "Cannot instantiate the type ArrayList<? extends OpDTO> "
问题描述
我有一个类
OpDTO
和其他几个 * DTO扩展了OpDTO
。 然后,我想要一个方法从这些子DTO的列表中提取某些元素,并将提取的元素返回到另一个列表中:
公开清单<?扩展OpDTO> getLastOp(List< ;? extends OpDTO> listDTOs){
List<扩展OpDTO> last = new ArrayList <?扩展OpDTO>(); //编译错误:无法实例化类型ArrayList<扩展OpDTO>
//处理
最后返回;
我想 ult
作为与 listDTOs
中元素类型相同的元素的列表,并且仅使用OpDTO的方法,但会产生编译错误:
无法实例化类型
ArrayList <?扩展OpDTO>
我也尝试过类似的操作:
public< T>列表与LT; T> getLastOp(List< T> listDTOs){
List< T> last = new ArrayList< T>();
//处理
返回最后;
}
但是我不能强制listDTOs中的元素成为OpDTO的子类,并且不能实例化T.
任何想法?
编辑
我也想到了将类型作为参数传递,然后我可以实例化它。这样做还是有些不好的做法?
private< T扩展OpDTO>列表与LT; T> getLastOp(List< T> listDTOs,Class<?extends OpDTO> clazz){
List< T> ult = new ArrayList< T>();
//处理
OpDTO op = clazz.newInstance();
//处理
ult.add((T)op);
op = listDTOs.get(i);
return ult;
名单< ;?扩展OpDTO>
是 List< T>
的协变视图;这意味着只要 T
匹配,任何 List< T>
类型都可以转换为它。 >
您不能创建这种类型的实例;您只能将其用作变量或参数类型来存放具体泛型类型的现有实例。
您需要创建一个带约束的泛型方法 $ b
public T 必须继承您的类扩展OpDTO>列表与LT; T> getLastOp(List< T> listDTOs){
According to what I've read, I think this can't be done, but I'd like to be sure.
I have a class OpDTO
and several other *DTO extends OpDTO
.
Then, I want to have a method to extract just certain elements from lists of these child DTOs, and return the extracted elements in another list:
public List<? extends OpDTO> getLastOp (List<? extends OpDTO> listDTOs) {
List<? extends OpDTO> last = new ArrayList<? extends OpDTO>(); //compile error: Cannot instantiate the type ArrayList<? extends OpDTO>
//processing
return last;
}
I want ult
to be a list of elements of the same kind as elements in listDTOs
, and use only OpDTO's methods, but it produces a compile error:
Cannot instantiate the type
ArrayList<? extends OpDTO>
I also tried doing something like:
public <T> List<T> getLastOp (List<T> listDTOs) {
List<T> last = new ArrayList<T>();
//processing
return last;
}
But then I can't enforce elements in listDTOs to be a subclass of OpDTO, and can't instantiate T. Any idea?
EDIT
It also occurred to me passing the type as parameter, then I can instantiate it. Would that be ok or is it some kind of bad practice?
private <T extends OpDTO> List<T> getLastOp (List<T> listDTOs, Class<? extends OpDTO> clazz) {
List<T> ult = new ArrayList<T>();
//processing
OpDTO op = clazz.newInstance();
//processing
ult.add((T) op);
op = listDTOs.get(i);
return ult;
}
List<? extends OpDTO>
is a covariant view of List<T>
; that means that any List<T>
type can be converted to it, as long as the T
matches.
You cannot create an instance of such a type; you can only use it as a variable or parameter type to hold existing instances of concrete generic types.
You need to create a generic method with a constraint that T
must inherit your class:
public <T extends OpDTO> List<T> getLastOp (List<T> listDTOs) {
这篇关于泛型的集合“无法实例化ArrayList类型”?扩展OpDTO> "的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!