Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast generics in a loop?

public static void someMethod(List < ? extends BaseDto > list) {
    for (ChildDto dto : list) {

    }
}

ChildDto extends BaseDto and here I'm sure its the list full of ChildDto.

I do know I can do something like this

for (TextApplicationDto dto : (List<TextApplicationDto>)list) {

but it does not look pretty.

Is there any better way of doing the casting?

like image 226
IAdapter Avatar asked Dec 22 '22 18:12

IAdapter


1 Answers

I think the best way would be:

public static void someMethod(List < ? extends BaseDto > list) {
    for (BaseDto dto : list) {
        ChildDto taDTO = (ChildDto)dto;
        // Whatever
    }
}

It also allows you to use instanceof to be sure that the list only contains ChildDto

like image 119
gabuzo Avatar answered Jan 07 '23 21:01

gabuzo