Zsolt Molnár
Zsolt Molnár

Reputation: 373

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?

Upvotes: 0

Views: 94

Answers (1)

Jorn Vernee
Jorn Vernee

Reputation: 33855

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;
}

Upvotes: 1

Related Questions