How to distinguish generics in a loop?

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

ChildDto extends BaseDto, and here I am sure that its list is populated by ChildDto.

I know I can do something like this

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

but he does not look very handsome.

Is there a better way to do a casting?

+4
source share
2 answers

I think the best way:

 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 make sure that only ChildDto

+8
source

ChildDto extends BaseDto , and here I am sure that its list is populated by ChildDto .

Then why does the argument type of this method not represent this knowledge?

Should it be List<ChildDto> or even List<? extends ChildDto> List<? extends ChildDto> .

How you do this is one solution, you can also use each return value yourself. Both are equally good at failing in roughly the same position:

 for (BaseDto bDto : list) 7 ChildDto dto = (ChildDto) bDto; // ... } 
+3
source

Source: https://habr.com/ru/post/1336429/


All Articles