I have ArrayList<Unit> units
. I want to write a function that would return all objects of specified subclass, which is used as parameter. However I can't get it to work. Here is what I have:
public static ArrayList<? extends Unit> getTheseUnits(Class<? extends Unit> specific_unit) {
ArrayList<specific_unit> res = new ArrayList<>(); //'specific_unit' is in red here. Adding '.class' or '.getClass()' after it does not resolve anything
for (Unit u : units){
if (u instanceof specific_unit){
res.add(u);
}
}
return res;
}
Filter them by 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 you want to make this method parametrized, use another 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 the second approach, you will get unchecked cast warning.
You can't use instanceof
on variable. Instead, you should use isInstance
.
Simply replace this line:
if (u instanceof specific_unit) {
with
if (specific_unit.isInstance(u)){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With