Question: Having a collection of abstract objects: `Set<Foo> foes;`

I want to have a method like this:

```
List<? extends Foo> getFoesByType(TypeEnum type);

```

I've tried:

```
List<? extends Foo> result = new ArrayList<>();
for(Foo f : foes) {
        if(f.getType() == type) {
            switch(type) {
            case TYPE1:
                f = (FooType1) f;
                break;
            case TYPE2:
                /*...*/
            }

            result.add(f);  
            /*The method add(capture#1-of ?) in the type 
            List<capture#1-of ?> is not applicable for the arguments (Foo)*/
        } 
}  

return result;

```

But I get an error.

I want to be able to do this: `List<FooType1> foesType1 = getFooesByType(TypeEnum.TYPE1);` Which would be the correct way?

Answer: 
You need to make your method generic:

```
private <T extends Foo> List<T> getFooesByType(EnumType type) {
    List<T> result = new ArrayList<>();
    for(Foo f : foes) {
        if(f.getType() == type) {
            switch(type) {
            case TYPE1:
                // do something, cast is not necessary
                break;
            case TYPE2:
                /*...*/
            }

            result.add((T) f); // cast here
        }
    }

    return result;
}

```
You can't do this. `? extends Foo` means that there could be any child of `Foo` class. You don't know what exactly it is and that's why you can't add to `List<? extends Foo>`.

But you can create array list and assign it to List and then return.

```
List<? extends Foo> getFoesByType(TypeEnum type) {
    List<Foo> result = new ArrayList<>();
    // add something to result list
    return result;
}

```