本文介绍了泛型的集合"无法实例化ArrayList& lt;吗?扩展OpDTO & quot;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我所读的内容,我认为这无法完成,但我想确定.我有一个类OpDTO和其他几个*DTO extends OpDTO.然后,我想有一种方法可以从这些子DTO的列表中仅提取某些元素,然后将提取的元素返回到另一个列表中:

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;
    }

我希望ult是与listDTOs中的元素种类相同的元素列表,并且仅使用OpDTO的方法,但是会产生编译错误:

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:

我也尝试做类似的事情:

I also tried doing something like:

public <T> List<T> getLastOp (List<T> listDTOs) {
        List<T> last = new ArrayList<T>();
        //processing

        return last;
    }

但是,然后我无法将listDTO中的元素强制为OpDTO的子类,并且无法实例化T.有什么主意吗?

But then I can't enforce elements in listDTOs to be a subclass of OpDTO, and can't instantiate T.Any idea?

编辑

我也想到将类型作为参数传递,然后可以实例化它.可以吗,还是不好的做法?

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>List<T>的协变视图;这意味着只要T匹配,任何List<T>类型都可以转换为它.
您不能创建这种类型的实例.您只能将其用作变量或参数类型来保存具体泛型类型的现有实例.

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.

您需要创建一个具有约束的通用方法,该约束 T必须继承您的类:

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) {

这篇关于泛型的集合&quot;无法实例化ArrayList&amp; lt;吗?扩展OpDTO &amp; quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 23:40