Zsolt Molnár Zsolt Molnár - 5 months ago 10
Java Question

Generic typed subcollection of a collection

I want to write a helper method that would return a genericly typed subcollection of an object collection, but I need some help with it!

Here is how I want to do it:

public static <T> Collection<T> getTypeFilteredSubCollection(Collection<Object> objects) {
Collection<T> typeFilteredCollection = new ArrayList<T>();
for(Object object : objects) {
if(object instanceof T) {
typeFilteredCollection.add((T)object);
}
}
return typeFilteredCollection;
}


The obvious problem is that generic types will disappear runtime, but you get the idea what I am trying to do.

Does anyone have an idea how to implement something like this?

Answer

You would have to pass the class of T along with it and use Class::isAssignableFrom:

public static <T> Collection<T> getTypeFilteredSubCollection(Collection<Object> objects, Class<T> clazz) {
    Collection<T> typeFilteredCollection = new ArrayList<T>();
    for(Object object : objects) {
        if(clazz.isInstance(object)) {
            typeFilteredCollection.add((T)object);
        }
    }
    return typeFilteredCollection;
}
Comments