Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List iteration - Generic logic

Tags:

java

generics

I have a list of beans (List<AClass>), from which I am creating two sub list based some logic which involves checking a field from the bean class, say action. if

bean.getAction.equals("true") - add to new sublist - List<AClass> listA
else - add to new sublist - List<AClass> listB

I have created a method for it and it works fine.

Now I have similar task for other Bean class as well where i have List<BClass> which also has action field and getAction method. I want to create a generic method which would cater to both these beans (and other similar beans as well).

How can I create such method?

like image 970
Ankit Avatar asked Jun 26 '26 19:06

Ankit


2 Answers

Use List<? extends ParentClass> where ParentClass is parent of AClass and BClass

like image 53
luboskrnac Avatar answered Jun 29 '26 07:06

luboskrnac


If AClass and BClass share a common base then a wilcard type can be used - List<? extends CommonBase>

like image 40
Reimeus Avatar answered Jun 29 '26 06:06

Reimeus