Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Method receive generic list and returns <capture of ?>

I’m trying to filter a List of objects that implements a Interface. And I trying to create a generic method for all the classes.

Something like:

interface SomeInterface {
    String getFlag();
}


class SomeObject implements SomeInterface {
    public String getFlag() {
        return "X";
    }
}


List<SomeObject> someObjectList = new ArrayList<>();

// Compilation error here
List<SomeObject> filterList = filterGenericList(someObjectList, "X");


private List<?> filterGenericList(List<? extends SomeInterface> objects, String flag) {
        return objects.stream()
                .filter(it -> it.getFlag().equals(flag))
                .collect(Collectors.toList());
}

How do I run away from the compilation Error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 Incompatible types. 
 Found: 'java.util.List<capture<?>>', 
 Required: 'java.util.List<SomeObject>'

>Solution :

When you return List<?> that means the method returns a list of some unknown type. Java doesn’t know that it’s the same type of list as the input list. To signal that, create a generic type T and have both the input and output lists be List<T>.

private <T extends SomeInterface> List<T> filterGenericList(List<T> objects, String flag) {
    return objects.stream()
        .filter(it -> it.getFlag().equals(flag))
        .collect(Collectors.toList());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading