Martin Thoma
Martin Thoma

Reputation: 136317

How can I get all instances of one type form Java List?

I have some parts in my code that look like this:

A, B and C extend D

public ArrayList<A> getA() {
    ArrayList<A> allElements = new ArrayList<A>();
    for (D el : listOfDs) {
        if (el instanceof A) {
            allElements.add((A) el);
        }
    }
    return allElements;
}

public ArrayList<B> getB() {
    ArrayList<B> allElements = new ArrayList<B>();
    for (D el : listOfDs) {
        if (el instanceof B) {
            allElements.add((B) el);
        }
    }
    return allElements;
}

public ArrayList<C> getC() {
    ArrayList<C> allElements = new ArrayList<C>();
    for (D el : listOfDs) {
        if (el instanceof C) {
            allElements.add((C) el);
        }
    }
    return allElements;
}

I would like to combine all of them to one method like this:

public <T> ArrayList<T> get() {
    ArrayList<T> allElements = new ArrayList<T>();
    for (D el : listOfDs) {
        if (el instanceof T) {
            allElements.add((T) el);
        }
    }
    return allElements;
}

Is this possible in Java?

At the moment I get

Cannot perform instanceof check against type parameter T. Use instead its erasure Object instead since further generic type information will be erased at runtime

and

Type safety: Unchecked cast from Node to T

Then I've tried this:

@SuppressWarnings("unchecked")
public <T> ArrayList<T> get(Class<T> clazz) {
    ArrayList<T> allElements = new ArrayList<T>();
    for(D o : listOfDs) {
        if (o.getClass() == clazz) {
            allElements.add((T) o);
        }
    }
    return allElements;
}

It doesn't throw any errors, but how can I call it? This did not work:

get(A);

Upvotes: 2

Views: 339

Answers (1)

missingfaktor
missingfaktor

Reputation: 92026

You could use Iterables.filter from Guava.

Example usage:

Iterable<X> xs = Iterables.filter(someIterable, X.class);

Since it's an open source library, you can check out the source to find what you are doing wrong.

Upvotes: 5

Related Questions