java - extracting all instances of subclass from arraylist -


i have arraylist<unit> units. want write function return objects of specified subclass, used parameter. can't work. here have:

public static arraylist<? extends unit> gettheseunits(class<? extends unit> specific_unit) {     arraylist<specific_unit> res = new arraylist<>();  //'specific_unit' in red here. adding '.class' or '.getclass()' after not resolve     (unit u : units){         if (u instanceof specific_unit){             res.add(u);         }     }     return res; } 

filter them class:

public static list<unit> getunitsbyclass(class<? extends unit> specificclass, list<? extends unit> units) {      return units.stream()                  .filter(e -> e.getclass().equals(specificclass))                  .collect(collectors.tolist()); } 

if want make method parametrized, use option:

public static <t extends unit> list<t> getunitsbyclass(class<t> specificclass, list<? extends unit> units) {      return (list<t>) units.stream()                            .filter(e -> e.getclass().equals(specificclass))                            .collect(collectors.tolist()); } 

but in second approach, unchecked cast warning.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -