Collections of generics

Posted by Luis Sep on Stack Overflow See other posts from Stack Overflow or by Luis Sep
Published on 2013-07-01T16:55:38Z Indexed on 2013/07/01 17:06 UTC
Read the original article Hit count: 319

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics