Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting all instances of subclass from arraylist

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;
}
like image 419
Coderino Javarino Avatar asked May 12 '15 11:05

Coderino Javarino


2 Answers

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.

like image 105
Alex Salauyou Avatar answered Sep 28 '22 11:09

Alex Salauyou


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)){
like image 29
Ori Lentz Avatar answered Sep 28 '22 09:09

Ori Lentz